-
Notifications
You must be signed in to change notification settings - Fork 0
вариант 1 #5
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
вариант 1 #5
Conversation
0972946 to
d6233a5
Compare
KirPyt
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.
Приветствую!
Работа выполнена на хорошем уровне! Далее опишу общие слова:
Некоторые замечания и советы актуальны и для остальных частей кода, поэтому стоит обратить внимание и на другие аналогичные места в коде, чтобы всё поправить. В целом я добавил несколько объемных рекомендаций, их можно попробовать учесть при наличии желания и времени, главное сильно не утонуть)
Если возникнут вопросы по ревью, то пишите мне в Пачку, обсудим
| private final CommentService commentService; | ||
|
|
||
| @Autowired | ||
| public CommentPrivateController(CommentService commentService) { |
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.
Если хотите, можно заменить данный конструктор аннотацией @RequiredArgsConstructor от lombok, тогда можно будет просто навесить данную аннотацию над классом и убрать данный код для конструктора
| } | ||
|
|
||
| @GetMapping | ||
| @ResponseStatus(HttpStatus.OK) |
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.
Данный статус возвращается по умолчанию, можно не писать явно
Далее аналогично
| @GetMapping | ||
| @ResponseStatus(HttpStatus.OK) | ||
| public List<CommentDto> getAllCommentsByUserId(@PathVariable Long userId, | ||
| @RequestParam(required = false, defaultValue = "0") Integer from, |
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.
При наличии defaultValue в required = false нет смысла
Далее аналогично
| @ResponseStatus(HttpStatus.OK) | ||
| public List<CommentDto> getAllCommentsByUserId(@PathVariable Long userId, | ||
| @RequestParam(required = false, defaultValue = "0") Integer from, | ||
| @RequestParam(required = false, defaultValue = "10") Integer size) { |
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.
Рекомендую перейти к проверке данных параметров с использованием штатных инструментов валидации в виде, например, аннотации @Positive или @PositiveOrZero. Разметите данную аннотацию в методе перед проверяемым параметров и она выполнит всю работу за Вас)
| @RequestParam List<Long> users, | ||
| @RequestParam(required = false) String text, | ||
| @RequestParam(required = false) | ||
| @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") |
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.
Рекомендую разместить паттерн в отдельной переменной, так можно будет удобно изменить её при необходимости
| @Getter | ||
| @Setter | ||
| public class NewCommentDto { | ||
| @NotBlank(message = "Текст комментария не может быть пустым") |
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.
Данная аннотация уже включает в себя @NotEmpty, можно убрать @NotEmpty
| import java.util.List; | ||
|
|
||
| @Component | ||
| public class CommentMapper { |
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.
Рекомендую подумать над тем, чтобы отказаться от @Component и перейти на аннотацию @UtilityClass, она подчеркнет, что данный класс служебный и сделает все методы статическими, а так же добавит приватный конструктор. Так же данная аннотация позволит не писать ключевое слово static и сделает это за Вас
Более подробно https://projectlombok.org/features/experimental/UtilityClass
К сожалению, от использования сервисов придется отказаться, но это лишний раз подстрахует Вас от случайных запросов к сервису в цикле
|
|
||
| @Service | ||
| @Slf4j | ||
| public class CommentServiceImpl implements CommentService { |
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.
Рекомендую подумать над тем, чтобы навесить аннотации для транзакций, чтобы Ваши методы стали транказционными:
Для этого Вы можете добавить аннотацию @Transactional над каждым методом, который необходимо выполнять в транзакции, либо можно просто разместить данную аннотацию над классом) Таким образом она будет использована для каждого метода. Так же рекомендую подумать над тем, чтобы для тех методов, где Вы используете только чтение данных, можно использовать @Transactional(readOnly = true)
Более подробно Вы можете почитать:
https://www.baeldung.com/transaction-configuration-with-jpa-and-spring
| text, | ||
| rangeStart, | ||
| rangeEnd, | ||
| PageRequest.of(from, size)); |
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.
Рекомендую сделать Ваши настройки пагинации немного проще:
Сформируйте класс, наследуемый от PageRequest и определите для него конструктор, принимающий параметры from и size. Данный класс будет реализовывать логику расчёта пагинации. Таким образом алгоритм расчёта пагинации будет инкапсулирован в данный класс.
Это позволит расширить стандартный spring класс пагинации под Вашу бизнес логику
KirPyt
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.
Приветствую!
В целом всё хорошо, но указал ещё некоторые моменты по коду, рекомендую попробовать их учесть. Рекомендую пробовать объемные исправления по коду в новой ветке, чтобы в случае чего иметь возможность отказаться от изменений. Рекомендацию по отказу циклических запросов к БД пробуйте только если позволяет время, в ином случае просто рекомендую иметь в виду на будущее
Если возникнут вопросы по ревью, то пишите в Пачку
| checkUser(userId); | ||
| List<Comment> comments = commentRepository.findByAuthorId(userId, PageRequest.of(0, 10)); | ||
| userService.findUserByIdForMapping(userId); | ||
| PageRequest pageRequest = CustomPageRequest.of(0, 10); |
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.
Не стоит явно подставлять числа, это плохая практика
| } | ||
|
|
||
| private List<Comment> getCommentsWithEventWithViewsAndRequests(List<Comment> comments) { | ||
| for (Comment comment : comments) { |
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.
Запросы в цикле - это плохая практика, так как каждый такой запрос требуется целого ряда действий для обращения к БД, стоит попробовать реализовывать всё за 1 запрос к БД, чтобы сильно не нагружать базу
| public List<CompilationDto> getAllCompilations(@RequestParam(required = false) Boolean pinned, | ||
| @RequestParam(required = false, defaultValue = "0") Integer from, | ||
| @RequestParam(required = false, defaultValue = "10") Integer size) { | ||
| @PositiveOrZero |
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.
Чтобы аннотации на подобие @PositiveOrZero над классом надо разместить аннотацию @Validated
| } else { | ||
| compilations = compilationRepository.findByPinned(pinned, PageRequest.of(from / size, size)); | ||
| } | ||
| for (Compilation compilation : compilations) { |
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.
Всё хорошо)
Это был Ваш заключительный проект на курсе, по этой причине хочу пожелать Вам удачи в дальнейшей карьере уже как разработчика, хорошего дня и быстрого профессионального роста! 🚀
| .annotation(event.getAnnotation()) | ||
| .category(CategoryMapper.toCategoryDto(event.getCategory())) | ||
| .confirmedRequests(event.getConfirmedRequests()) | ||
| //.confirmedRequests(event.getConfirmedRequests()) |
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.
Не рекомендую оставлять закомментированные участки кода
| private Long count; | ||
| private Long eventId; | ||
|
|
||
| public ConfirmedRequest(Long eventId, Long count) { |
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.
Если хотите, данный конструктор можно заменить при помощи аннотации @AllArgsConstructor
No description provided.