Skip to content

Toporov, 3 quest#5

Open
aplih wants to merge 6 commits intodemologin:mainfrom
aplih:toporov
Open

Toporov, 3 quest#5
aplih wants to merge 6 commits intodemologin:mainfrom
aplih:toporov

Conversation

@aplih
Copy link

@aplih aplih commented Jan 26, 2026

No description provided.

Copy link
Owner

@demologin demologin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Общий вывод по проекту

Проект демонстрирует хорошее понимание основ работы с Java Servlets и сессиями. Успешно реализовал дерево решений квеста и механизм переходов между состояниями. Однако архитектура сильно перегружена логикой в слое контроллеров (сервлетов), что затрудняет поддержку и расширение.

Основные рекомендации:

Выделение бизнес-логики: Перенесите управление состоянием квеста и поиск данных из сервлетов в сервисный слой (QuestService).

Использование фильтров: Вынесите проверку сессии пользователя в Filter, чтобы не дублировать код в каждом сервлете.

Уход от "магических чисел": Используйте Enum для статусов игры и константы для ключей сессии.

Логирование: Замените отсутствие уведомлений или потенциальные System.out.println на полноценный логгер (например, SLF4J).

Проект выглядит крепким для начального уровня, но применение принципов SOLID и паттернов проектирования сделает его профессиональным.

Итоговая оценка: A

import java.util.HashMap;
import java.util.Map;

public class Quest {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поля 'name' и 'prologue' должны быть final, так как они не меняются после создания объекта. Это обеспечит неизменяемость (immutability). [INFO]

public class Quest {
private String name;
private String prologue;
private Map<Integer, QuestStep> steps;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Рекомендуется использовать интерфейс List или Collection вместо конкретной реализации HashMap в объявлении типа поля, если порядок не важен, или Map, если важен доступ по ID. [INFO]

public class QuestStep {
private int id;
private String text;
private Map<String, Integer> options;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Использование Map<String, Integer> для опций связывает логику переходов с текстом кнопок. Лучше создать отдельный класс Option с полями text и nextStepId. [WARNING]

private boolean isEnd;
private boolean isWin;

public QuestStep(int id, String text, Map<String, Integer> options, boolean isEnd, boolean isWin) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Конструктор принимает слишком много параметров. Стоит рассмотреть паттерн Builder для более удобного создания объектов QuestStep. [INFO]


@WebServlet("/restart")
public class RestartServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отсутствует логирование процесса перезапуска. Рекомендуется использовать SLF4J/Logback вместо пустых строк или отсутствия уведомлений о действиях пользователя. [WARNING]

import java.io.IOException;

@WebServlet("/restart")
public class RestartServlet extends HttpServlet {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Класс не содержит комментариев Javadoc, описывающих его назначение. [INFO]

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String choice = request.getParameter("choice");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Параметр 'choice' из запроса никак не фильтруется, что потенциально может привести к XSS, если эти данные будут выведены обратно без экранирования. [WARNING]

@@ -0,0 +1,225 @@
package com.javarush.toporov.quest.util;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Класс утилит должен иметь приватный конструктор, чтобы предотвратить создание экземпляров. [INFO]

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class QuestTest {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Имя тестового класса QuestTest хорошее, но стоит добавить тесты на негативные сценарии (например, несуществующий ID шага). [INFO]

import java.io.IOException;

@WebServlet("/start")
public class StartServlet extends HttpServlet {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Название сервлета StartServlet корректно, но стоит придерживаться единого стиля именования URL (кебаб-кейс или кэмел-кейс). [INFO]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants