Conversation
ConsoleRunner used to run a console application
In ShowMenu implemented reading from the console. In Controller implemented exception catching. In Actions implemented exception generation
| public static final String DEFAULT_FOLDER = System.getProperty("user.dir") + File.separator + "text" + File.separator; | ||
|
|
||
| public static final List<Character> ALPHABET_LIST = new ArrayList<>(); | ||
|
|
There was a problem hiding this comment.
Вместо ручного заполнения списка в static-блоке используйте Stream API: ruAlphabet.toLowerCase().chars().mapToObj(c -> (char)c).toList(). Это короче и использует современные возможности Java.
|
|
||
| import com.javarush.golikov.entite.Result; | ||
|
|
||
| public interface MenuCommands { |
There was a problem hiding this comment.
Используйте sealed interface для MenuCommands. Это гарантирует, что список команд ограничен и известен заранее, что улучшает безопасность и дизайн приложения (Java 17+).
| fileWriter.write(Constants.ALPHABET[index]); | ||
| } else if (character == '\n') { | ||
| fileWriter.write(character); | ||
| } |
There was a problem hiding this comment.
Для вычисления индекса при отрицательных сдвигах используйте Math.floorMod(index + key, length). Это чище и надежнее, чем ручные манипуляции с Math.abs.
|
|
||
| public Actions() { | ||
| actionMap.put(0, new Encryption()); | ||
| actionMap.put(1, new Decoding()); |
There was a problem hiding this comment.
Используйте Map.of(0, new Encryption(), ...) для создания неизменяемой карты. Это более современный и лаконичный способ инициализации коллекций в Java.
| while ((value = reader.read()) > -1) { | ||
| char character = (char) value; | ||
| if (Constants.ALPHABET_LIST.contains(character)) { | ||
| int index = Constants.ALPHABET_LIST.indexOf(character); |
There was a problem hiding this comment.
Вызов Files.newBufferedReader внутри цикла приводит к многократному открытию файла. Прочитайте содержимое файла один раз перед циклом для повышения производительности.
| public Result run() { | ||
| int menuIndex = showMenu.getMenuItem(); | ||
| String[] parametrises = showMenu.getParameterises(menuIndex == 0 || menuIndex == 1); | ||
| return controller.doAction(menuIndex, parametrises); |
There was a problem hiding this comment.
Условие menuIndex == 0 || menuIndex == 1 является 'хрупким'. Если порядок в меню изменится, логика сломается. Используйте полиморфизм для определения необходимости ключа.
| return actionMap.get(actionIndex); | ||
| } catch (IllegalArgumentException e) { | ||
| throw new ApplicationExceptions("Пункт меню не реализован!", e); | ||
| } |
There was a problem hiding this comment.
Метод actionMap.get() не выбрасывает IllegalArgumentException. Блок try-catch здесь бесполезен. Достаточно проверки на null или containsKey.
| Path sourceFile = Path.of(source); | ||
| Path targetFile = Path.of(target); | ||
|
|
||
| try (BufferedReader fileReader = Files.newBufferedReader(sourceFile); |
There was a problem hiding this comment.
Вместо конкатенации путей через +=, используйте Path.resolve() или Path.of(dir, filename). Это кроссплатформенный и безопасный способ работы с путями.
| @@ -0,0 +1,12 @@ | |||
| package com.javarush.golikov.entite; | |||
|
|
|||
| public record Result(String message, String resultCode) { | |||
There was a problem hiding this comment.
Record автоматически генерирует toString. Переопределяйте его только если вам нужен специфический формат вывода, отличный от стандартного.
| if (isKeyNeeded){ | ||
| System.out.println("Введите ключ шифрования/дешифрования"); | ||
| parameterises[2] = scanner.nextLine(); | ||
| } |
There was a problem hiding this comment.
Использование System.in напрямую через Scanner в ShowMenu затрудняет юнит-тестирование. Передавайте Scanner или InputStream через конструктор.
demologin
left a comment
There was a problem hiding this comment.
поставила оценку C преимущественно из-за сроков, но и объем проекта тоже меньше ожидаемого
No description provided.