-
Notifications
You must be signed in to change notification settings - Fork 27
Alimov #4
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?
Alimov #4
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package com.javarush.alimov.quest; | ||
|
|
||
| public class GameLogic { | ||
|
|
||
| public static GameResult next(GameState current, String answer) { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Метод next() содержит сложную структуру switch-case, управляющую переходами состояний. Это классическое нарушение принципа открытости/закрытости (OCP). Рекомендуется использовать паттерн State. |
||
| return switch (current) { | ||
| case START -> new GameResult(GameState.UFO_CHALLENGE, null); | ||
|
|
||
| case UFO_CHALLENGE -> { | ||
| if ("accept".equals(answer)) { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Строковые литералы для ответов (например, 'accept', 'go') разбросаны по всему коду. Рекомендуется использовать перечисления (Enum) для возможных действий игрока. |
||
| yield new GameResult(GameState.BRIDGE_CHOICE, null); | ||
| } else { | ||
| yield new GameResult(GameState.LOSE, "Ты отклонил вызов. Поражение."); | ||
| } | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Текстовые сообщения для пользователя жестко прописаны в логике. Для поддержки интернационализации (i18n) их следует вынести в ResourceBundle. |
||
|
|
||
| case BRIDGE_CHOICE -> { | ||
| if ("go".equals(answer)) { | ||
| yield new GameResult(GameState.IDENTITY_CHOICE, null); | ||
| } else { | ||
| yield new GameResult(GameState.LOSE, "Ты не пошёл на переговоры. Поражение."); | ||
| } | ||
| } | ||
|
|
||
| case IDENTITY_CHOICE -> { | ||
| if ("truth".equals(answer)) { | ||
| yield new GameResult(GameState.WIN, "Тебя вернули домой. Победа!"); | ||
| } else { | ||
| yield new GameResult(GameState.LOSE, "Твою ложь разоблачили. Поражение."); | ||
| } | ||
| } | ||
|
|
||
| default -> new GameResult(GameState.START, null); | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package com.javarush.alimov.quest; | ||
|
|
||
| public record GameResult(GameState state, String message) { | ||
|
|
||
| } | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package com.javarush.alimov.quest; | ||
|
|
||
| import jakarta.servlet.http.*; | ||
| import jakarta.servlet.annotation.*; | ||
| import jakarta.servlet.*; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Использование wildcard import (jakarta.servlet.http.*) не рекомендуется, так как это затрудняет понимание используемых зависимостей. |
||
|
|
||
| import java.io.IOException; | ||
|
|
||
| @WebServlet("/game") | ||
| public class GameServlet extends HttpServlet { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Методы doGet и doPost содержат дублирующийся код вызова Dispatcher. Общую логику перехода можно вынести в защищенный метод. |
||
| @Override | ||
| protected void doGet(HttpServletRequest req, HttpServletResponse resp) | ||
| throws ServletException, IOException { | ||
| req.getRequestDispatcher("/WEB-INF/game.jsp").forward(req, resp); | ||
| } | ||
|
|
||
| @Override | ||
| protected void doPost(HttpServletRequest req, HttpServletResponse resp) | ||
| throws ServletException, IOException { | ||
|
|
||
| HttpSession session = req.getSession(); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Отсутствует логирование действий пользователя или ошибок. Использование SLF4J помогло бы в диагностике проблем на сервере. |
||
| GameState state = (GameState) session.getAttribute("state"); | ||
| if (state == null) state = GameState.START; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Использование жестко закодированного состояния по умолчанию напрямую в контроллере нарушает инкапсуляцию. Рекомендуется вынести логику инициализации в GameLogic. |
||
|
|
||
| String answer = req.getParameter("answer"); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Параметр 'answer' получается напрямую из запроса без валидации. Это потенциальная уязвимость, если данные будут использоваться в выводе без экранирования. |
||
| GameResult result = GameLogic.next(state, answer); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Контроллер напрямую вызывает статический метод GameLogic.next. Это затрудняет тестирование и нарушает принцип инверсии зависимостей. Стоит использовать внедрение зависимостей. |
||
|
|
||
| session.setAttribute("state", result.state()); | ||
| session.setAttribute("message", result.message()); | ||
|
|
||
| if (result.state() == GameState.WIN || result.state() == GameState.LOSE) { | ||
| Integer gamesPlayed = (Integer) session.getAttribute("gamesPlayed"); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Счетчик игр хранится в сессии как Integer. При конкурентных запросах (хотя здесь это маловероятно) возможны проблемы. Стоит рассмотреть атомарные типы или сервисный слой. |
||
| session.setAttribute("gamesPlayed", gamesPlayed == null ? 1 : gamesPlayed + 1); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Логика инкремента счетчика игр смешана с логикой обработки HTTP-запроса. Данную операцию следует вынести в отдельный сервисный слой. |
||
| req.getRequestDispatcher("/WEB-INF/result.jsp").forward(req, resp); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Пути к JSP ресурсам ('/WEB-INF/game.jsp') дублируются в коде. Целесообразно определить их как константы, чтобы избежать ошибок при опечатках. |
||
| } else { | ||
| req.getRequestDispatcher("/WEB-INF/game.jsp").forward(req, resp); | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package com.javarush.alimov.quest; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Перечисление GameState содержит как промежуточные состояния, так и терминальные (WIN, LOSE). Стоит рассмотреть разделение логики навигации и статуса завершения. |
||
|
|
||
| public enum GameState { | ||
| START, | ||
| UFO_CHALLENGE, | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Названия состояний (например, UFO_CHALLENGE) выбраны удачно и соответствуют предметной области квеста. |
||
| BRIDGE_CHOICE, | ||
| IDENTITY_CHOICE, | ||
| WIN, | ||
| LOSE | ||
| } | ||
This file was deleted.
This file was deleted.
This file was deleted.
This file was deleted.
This file was deleted.
This file was deleted.
This file was deleted.
This file was deleted.
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.
Класс GameLogic не имеет приватного конструктора, хотя содержит только статические методы. Следует предотвратить создание экземпляров утилитного класса.