Рефакторинг интеерпретатора brainfuck (clean code)

112
21 декабря 2019, 04:00

У меня есть относительно чистый код интерпретатора brainFuck на java, могли бы вы дать несколько советов по его улучшению в плане чистоты кода, и, если не сложно, посоветовать книги/ресурсы для развития в эту сторону

public class Main {
    public static void main(String[] args) {
        String hello = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
        Memory memory = Memory.getInstance();
        CommandFactory commandFactory = new CommandFactory();
        List<Command> commands = commandFactory.createFor(hello);
        for (Command command : commands) {
            command.execute(memory);
        }
    }
}

public class CommandFactory {
    public List<Command> createFor(String programCode) {
        List<Command> list = new ArrayList<Command>();
        int level = 0;
        int startLoopIndex = 0;
        char[] input = programCode.toCharArray();
        for (int i = 0; i < programCode.length(); i++) {
            if (input[i] == '[') {
                if (level == 0)
                    startLoopIndex = i;
                level++;
            } else if (input[i] == ']') {
                level--;
                if (level == 0) {
                    String loopInput = programCode.substring(startLoopIndex + 1, i);
                    list.add(new LoopCommand(createFor(loopInput)));
                }
            } else if (level == 0) {
                list.add(getSimpleCommand(input[i]));
            }
        }
        return list;
    }
    private Command getSimpleCommand(Character character) {
        if (character == '+') {
            return new PlusCommand();
        } else if (character == '>') {
            return new NextCommand();
        } else if (character == '<') {
            return new PreviousCommand();
        } else if (character == '-') {
            return new MinusCommand();
        } else if (character == '.') {
            return new PrintCommand();
        }
        return new EmptyCommand();
    }
}


 public class Memory {
private int dataPointer;
private byte[] memory = new byte[65535];
private static Memory instance;
private Memory() {
}
public static Memory getInstance() {
    if (instance == null) {
        instance = new Memory();
    }
    return instance;
}
public byte getCurrentMemoryByte() {
    return memory[dataPointer];
}
public void moveNext() {
    dataPointer = (dataPointer == memory.length - 1) ? 0 : dataPointer + 1;
}
public void moveBack() {
    dataPointer = (dataPointer == 0) ? memory.length - 1 : dataPointer - 1;
}
public void printValue() {
    System.out.print((char) memory[dataPointer]);
}
public void setMemory(byte[] mem) {
    this.memory = mem;
}
public int getDataPointer() {
    return dataPointer;
}
public void setDataPointer(int dataPointer) {
    this.dataPointer = dataPointer;
}
public void increment() {
    ++memory[dataPointer];
}
public void decrement() {
    --memory[dataPointer];
}
}

public class LoopCommand implements Command {
    List<Command> commands;
public LoopCommand(List<Command> commands) {
    this.commands = commands;
}
public void execute(Memory memory) {
    do {
        for (Command command : commands) {
            command.execute(memory);
        }
    } while (memory.getCurrentMemoryByte() != 0);
}
}
READ ALSO
Не удалаяется файл БД при удалении приложения (Android)

Не удалаяется файл БД при удалении приложения (Android)

Работаю с готовой БДПри запуске приложения копирую из Assets в каталог БД приложения по пути:

143
Полиморфизм в Java и перегрузка

Полиморфизм в Java и перегрузка

Относиться ли перегрузка метода к полиморфизму в языке Java? Как я знаю только переопределение метода относиться к полиморфизму в языке Java, а перегрузка...

217
Как закрыть все поля Toast при закрытии приложения?

Как закрыть все поля Toast при закрытии приложения?

У меня в приложении при определённых обстоятельствах вылезает поле toast с подсказкамиДопустим, поле toast ещё отображается, а приложение закрыли...

132
Идентификация клиента приложения

Идентификация клиента приложения

Как идентифицировать пользователя приложения? К примеру: Марка телефона + IP не являются уникальнымиКак это делает Firebase? Как они идентифицируют...

145