-
Notifications
You must be signed in to change notification settings - Fork 0
Sprint 7 solution in file manager #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
* src/manager/InMemoryHistoryManager.java
+ Реализован двусвязный список + HashMap<id,Node>
+ add(task) теперь удаляет дубликаты через removeNode за O(1)
+ remove(id) — новый метод HistoryManager
* src/manager/TaskManager.java
+ в интерфейс добавлен void remove(int id)
* src/manager/InMemoryTaskManager.java
+ вызовы historyManager.remove(...) в removeTask / removeEpic / removeSubtask
* src/manager/HistoryManager.java
+ объявлен метод remove(int id)
* tests
+ HistoryManagerTest — проверяет отсутствие дублей и порядок
+ InMemoryTaskManagerTest — проверка очистки истории при удалении,
истории > 10, дубль-просмотров
+ TaskManagerHistoryIntegrationTest — интеграция: удаление эпика убирает
эпик и все Subtask'и из истории
Issue: sprint-6 / ТЗ «неограниченная история без дублей»
LexLippi
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Привет!
Неплохая работа!
Есть некоторое количество замечаний. которые необходимо исправить!
Желаю удачи!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Плохо, что эти классы попали в git, локально они уместны, но тут не нужны
| } | ||
|
|
||
| private void restore() { | ||
| if (!file.exists()) return; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В соответствии с Google Java Code Style надо добавить скобки:
https://google.github.io/styleguide/javaguide.html#s4.1.1-braces-always-used
| List<Epic> epics = new ArrayList<>(); | ||
| List<Task> tasks = new ArrayList<>(); | ||
| List<Subtask> subtasks = new ArrayList<>(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Такое форматирование выглядит весьма странно :)
| r.readLine(); // пропускаем заголовок | ||
| String line; | ||
| while ((line = r.readLine()) != null) { | ||
| if (line.isBlank()) continue; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Аналогично про скобки
| Task t = fromCsv(line); | ||
| switch (t.getType()) { | ||
| case EPIC -> epics.add((Epic) t); | ||
| case TASK -> tasks.add(t); | ||
| case SUBTASK -> subtasks.add((Subtask) t); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Довольно странным выглядит сначала erasure типа до Task а потом снова кастинг его к конкретному значению, кажется, что этого можно избежать
|
|
||
|
|
||
| /*───────────── CSV ─────────────*/ | ||
| private static String toCsv(Task t) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лучше в каждом типе задачи сделать метод toCsv тогда сможем воспользоваться преимуществами полиморфизма
| for (Epic e : epics) super.addNewEpic(e); | ||
| for (Task t : tasks) super.addNewTask(t); | ||
| for (Subtask s : subtasks) super.addNewSubtask(s); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
При использовании этих методов изменятся существующие идентификаторы задач, чего бы не хотелось
| import java.nio.file.Files; | ||
|
|
||
| /** Менеджер с автосохранением в CSV-файл. */ | ||
| public class FileBackedTaskManager extends InMemoryTaskManager { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В целом советую добавить в Idea сheckstyle-плагин, он помогает избежать ошибок код стайла
… методах, сохранение исходных id
…restore (если восстановление)
…а O(1); чистка импортов
…обы убрать предупреждения
… minimal IDEA files
LexLippi
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Привет!
Хорошая работа!
Желаю удачи в следующих спринтах!
Sprint 7 – File Manager: автосохранение в CSV + фиксы
Суть
Добавил автосохранение состояния в файл с восстановлением после перезапуска
Раньше данные жили только в памяти и пропадали
Основные изменения
Новый FileBackedTaskManager
Автосохранение в CSV после каждого изменения
Восстановление состояния с сохранением оригинальных ID
Поддержка пустых файлов и всех типов задач
Модель
Сериализация через toCsvRow()
Инкапсуляция subtaskIds в Epic
Валидация epicId в Subtask
Фиксы
Чистка истории при удалении задач
Корректная работа nextId после восстановления
Унифицированный стиль кода
Формат CSV
Как проверить
1 Запустить Main → создастся tasks.csv
2 Перезапустить через loadFromFile() → данные восстановятся
3 Все тесты зеленые (./gradlew test)
Важные моменты
Публичный API не изменился
Нет экранирования спецсимволов в CSV (по ТЗ)
Относительный путь к файлу (можно доработать)
Чек-лист
id+ корректныйnextId.gitignoreи чистка артефактов