Skip to content

Tarasenko#13

Open
nikitatarasenko108 wants to merge 1 commit intodemologin:mainfrom
nikitatarasenko108:tarasenko
Open

Tarasenko#13
nikitatarasenko108 wants to merge 1 commit intodemologin:mainfrom
nikitatarasenko108:tarasenko

Conversation

@nikitatarasenko108
Copy link

No description provided.

@nikitatarasenko108 nikitatarasenko108 changed the title quest Tarasenko Feb 10, 2026
@demologin
Copy link
Owner

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

Представленный код демонстрирует хорошее владение базовым синтаксисом Java и продвинутыми механизмами.

Проект демонстрирует глубокое понимание принципов ООП и работы Java Servlet API.

Однако, основной проблемой является игнорирование многопоточной специфики сервлетов: использование static полей и обычных HashMap для хранения данных пользователей и квестов приведет к ошибкам при реальном использовании. Пакет можно было сделать свой ;)

Рекомендации:

  • Продолжить углубление знаний по паттернам проектирования
  • Изучить асинхронное программирование более глубоко
  • Уделить внимание документированию кода

Итоговая оценка: A (с авансом на будущее ;)

import java.util.concurrent.atomic.AtomicInteger;

public class Quest {
static AtomicInteger atomicInteger = new AtomicInteger(0);
Copy link
Owner

Choose a reason for hiding this comment

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

Статическое поле 'atomicInteger' для генерации ID разделяется между всеми экземплярами класса в рамках JVM. Это может привести к непредсказуемому поведению в многопоточной среде сервлетов. Лучше перенести генерацию ID на уровень репозитория.

this.name = name;
}

Map<Integer, Question> questions = new HashMap<>();
Copy link
Owner

Choose a reason for hiding this comment

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

Поля 'questions' и 'loseMap' имеют доступ по умолчанию (package-private). Согласно принципу инкапсуляции, их следует сделать private.

public Question getQuestionById(int i){
return questions.get(i);
}
public void crete(int i,String first, String second, String third, String lose){
Copy link
Owner

Choose a reason for hiding this comment

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

Опечатка в названии метода 'crete'. Следует исправить на 'create' для соблюдения чистоты кода и читаемости.




private final Map<Integer, Quest> questMap = new HashMap<>();
Copy link
Owner

Choose a reason for hiding this comment

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

Использование HashMap в многопоточной среде (сервлеты) небезопасно. Рекомендуется заменить на ConcurrentHashMap для предотвращения Race Condition.

return questMap.get(id);
}

public void crate(Quest quest){
Copy link
Owner

Choose a reason for hiding this comment

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

Опечатка в названии метода 'crate'. Следует переименовать в 'create'.


@WebServlet("/quest")
public class NewQuest extends HttpServlet {
static int num;
Copy link
Owner

Choose a reason for hiding this comment

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

Объявление переменных 'num' и 'name' как static в сервлете — критическая ошибка. Сервлет создается в единственном экземпляре, и эти данные будут перезаписываться при одновременном обращении разных пользователей.


@WebServlet("/play")
public class Play extends HttpServlet {
int qid;
Copy link
Owner

Choose a reason for hiding this comment

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

Поле 'qid' на уровне класса сервлета не является потокобезопасным. Значение, установленное одним пользователем, может быть прочитано другим. Данные состояния должны храниться в HttpSession.

int qid;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("=== PLAY POST ===");
Copy link
Owner

Choose a reason for hiding this comment

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

Использование System.out.println для логирования недопустимо в продакшн-коде. Рекомендуется использовать логгер (например, SLF4J + Logback).

try{
qid = Integer.parseInt(req.getParameter("questId"));
}
catch (Exception e){
Copy link
Owner

Choose a reason for hiding this comment

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

Пустой блок catch (Exception e) 'проглатывает' ошибки. Это затрудняет отладку. Необходимо как минимум логировать исключение.

return;
}

if ( Create.questRepository.getById(qid).getQuestionById(que+1 ) == null){
Copy link
Owner

Choose a reason for hiding this comment

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

Сложная цепочка вызовов (Create.questRepository.getById...). Это нарушает закон Деметры. Следует извлечь объект Quest в локальную переменную.

@WebServlet("/create")
public class Create extends HttpServlet {

public static QuestRepository questRepository = new QuestRepository();
Copy link
Owner

Choose a reason for hiding this comment

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

Публичное статическое поле 'questRepository' — это нарушение инкапсуляции и плохая практика управления зависимостями. Репозиторий должен внедряться через конструктор или Winter.find.

public class Create extends HttpServlet {

public static QuestRepository questRepository = new QuestRepository();
Quest quest;
Copy link
Owner

Choose a reason for hiding this comment

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

Поле 'quest' в сервлете приведет к состоянию гонки (Race Condition). Перенесите его в локальную область видимости метода doPost.



public class Answer {
String text;
Copy link
Owner

Choose a reason for hiding this comment

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

Поля 'text' и 'id' не имеют модификаторов доступа. Их следует сделать private final.

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