Skip to content

Feature comments - #3

Open
SugarFoxy wants to merge 13 commits into
mainfrom
feature_comments
Open

Feature comments#3
SugarFoxy wants to merge 13 commits into
mainfrom
feature_comments

Conversation

@SugarFoxy

Copy link
Copy Markdown
Owner

No description provided.

@LexLippi LexLippi left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Привет!

Неплохая работа, но есть несколько замечаний, которые необходимо исправить, и вопросы на которые необходимо ответить.

Желаю удачи!!!

@@ -1,10 +1,10 @@
DROP TABLE IF EXISTS compilation_events,compilations,requests,events,categories,users;
DROP TABLE IF EXISTS rating, comments, compilation_events,compilations,requests,events,categories,users;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Может можно как-то не удалять таблицы?

Таким образом при каждом разворачивании наших сервисов данные будут теряться, а польо=зователи негодовать, не хотелось бы этого :)

CREATE TABLE IF NOT EXISTS comments
(
id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
text VARCHAR(2000) NOT NULL,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если мы пишем PostgreSQL-специфичный скрипт, то лучше не называть колонку text, так как в PostgreSQL есть тип данных с таким же названием, а это считается bad practice в любом ЯП.

Поэтому стоит подобрать какое-нибудь синонимичное название или на крайний случай comment_text

text VARCHAR(2000) NOT NULL,
user_id BIGINT NOT NULL,
event_id BIGINT NOT NULL,
comment_time TIMESTAMP WITHOUT TIME ZONE,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Кажется, что оно не может быть null

state VARCHAR,
title VARCHAR(255) NOT NULL,
views BIGINT,
comment_switch BOOLEAN,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

  1. Что означает это поле?
  2. Может ли оно быть null?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Это по сути своей рубильник который выключает и включает комментарии.
Была невнимательна null быть не может

if (!event.getCommentSwitch()) {
return new ArrayList<>();
}
Sort sort1 = Sort.by(DESC, "commentTime");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А почему не просто sort?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Изначально был аргумент с таким же название, потом оно мне не понравилось и я изменила, а эта переменная осталась

}

@Override
public CommentDto updateComment(Long userId, Long commId, NewAndUpdateCommentDto dto) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

  1. commentId можно польностью написать
  2. а точно нужно такое сложное название для типа данных объекта dto? Может просто CommentDto?
    Или на крайний случай просто UpdateCommentDto?

User user = objectCreator.getUserById(userId);
Event event = objectCreator.getEventById(dto.getEventId());

if (!comment.getCommentator().equals(user)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

можно сравнить на уровне идентификаторов, и если возникает ошибка, то не делать лишний запрос по получению пользователя

throw new BadRequestException(String
.format("Только комментатор id = %d может изменить коментарий id = %d ", userId, commId));
}
if (!comment.getEvent().equals(event)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Аналогичное замечание про сравнение идентификаторов

Comment on lines +72 to +77
User user = objectCreator.getUserById(userId);

if (!comment.getCommentator().equals(user)) {
throw new BadRequestException(String
.format("Только комментатор может удалить коментарий id = %d ", commId));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тоже самое, что и выше

@LexLippi LexLippi left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Привет!

Еще пару замечаний накинул!

Желаю удачи!!!

Comment on lines +29 to +32
public List<OutCommentDto> getCommentByEvent(@NotNull @RequestParam Long eventId,
@RequestParam(defaultValue = "false") Boolean rating,
@PositiveOrZero @RequestParam(defaultValue = "0") int from,
@Positive @RequestParam(defaultValue = "10") int size) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Почему какие-то поля объектные, а какие-то примитивные, тем более если eventId не может быть null. Во всех контроллерах это вижу, давай к какому-то одному стилю придем

return service.updateComment(userId, commId, dto);
}

@DeleteMapping("/{commId}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Может на commentId всё-таки переделаем?


@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public OutCommentDto createComment(@PathVariable Long userId,

This comment was marked as resolved.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Спасибо что подсказал. Не дружу с английским. Поэтому и названия кривые


@Setter
@Getter
@NoArgsConstructor

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вот это ты где-то используешь? Если нет, то лучше удалить это из всех классов

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Когда дто приходи и десериализуется требует конструкторы. Неужели это так нагружает систему? Могу удалить билдер он тут не нужен.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

На самом деле систему это не нагружает, тут проблема в том, что такой доступный зоопарк возможностей по конструированию объекта приводит к тому, что каждый разработчик создает объекты по своему и это больно потом одному человеку сводить, когда надо довести горящий релиз до логического завершения.

А так в целом билдер это отличный шаблон, очень удобно с ним работать, и вообще это довольно интересная концепция.

Comment on lines +11 to +12
@AllArgsConstructor
@Builder

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

И Setter, и Builder, и AllArgsConstructor, может от чего-то можно отказаться?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

только от билдера. Хотя для написания тестов он был бы удобен. (очень он мне полюбился)

Comment on lines +11 to +12

public class CommentMapper {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если все методы статические, то лучше сделать пустой конструктор этого класса приватным, чтобы везде гарантированно использовать его, как синглтон:

https://en.wikipedia.org/wiki/Singleton_pattern

Либо можно вместо класса использовать enum, как синглтон. Кстати, чтобы никто не испортил поведение нашего класса, то лучше пометить его как final, чтобы у него не могло быть наследников.

https://www.geeksforgeeks.org/advantages-and-disadvantages-of-using-enum-as-singleton-in-java/

@Override
public OutCommentDto createComment(Long userId, InputCommentDto dto) {
Event event = objectCreator.getEventById(dto.getEventId());
if (!event.getCommentSwitch()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Наверное лучше commentAvailable, чтобы было понятнее, а то switch немного пугает

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Это не я, это гугл переводчик тебя испугал))))).

Я буду скучать по твоим ревью :`(
Спасибо большое за твой труд и прости за кровавые слезы при прочтении моего кода =D

@LexLippi LexLippi left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Привет!

Отличная работа!

Дипломный проект сдан!

Желаю удачи в свободном плавании!

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.

3 participants