-
Notifications
You must be signed in to change notification settings - Fork 0
1) Создал новую ветку add-friends-likes. #2
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
Conversation
ViktorSalk
commented
Jan 20, 2025
- Создал интерфейсы FilmStorage и UserStorage, в которых будут определены методы добавления, удаления и модификации объектов. 3) Создал классы InMemoryFilmStorage и InMemoryUserStorage, имплементирующие новые интерфейсы, и перенес всю логику хранения, обновления и поиска объектов. 4) Создал UserService и FilmService для обеспечения возможности пользователям добавлять друг друга в друзья и ставить фильмам лайки. 5) Создал класс ValidationService для фокусировки на проверке конкретных правил валидации данных в изоляции: Проверки длины описания фильма, Валидации имени фильма, Проверки email пользователя, Валидации логина и т.д. 6) Создал тесты на новую фичу: тесты фильма, тесты пользователя, тесты лайков, тесты друзей.
2) Создал интерфейсы FilmStorage и UserStorage, в которых будут определены методы добавления, удаления и модификации объектов. 3) Создал классы InMemoryFilmStorage и InMemoryUserStorage, имплементирующие новые интерфейсы, и перенес всю логику хранения, обновления и поиска объектов. 4) Создал UserService и FilmService для обеспечения возможности пользователям добавлять друг друга в друзья и ставить фильмам лайки. 5) Создал класс ValidationService для фокусировки на проверке конкретных правил валидации данных в изоляции: Проверки длины описания фильма, Валидации имени фильма, Проверки email пользователя, Валидации логина и т.д. 6) Создал тесты на новую фичу: тесты фильма, тесты пользователя, тесты лайков, тесты друзей.
2) Добавил проверку на нулевое значение лайков 3) Упростил добавление и удаление в filmStorage и InMemoryUserStorage
2) Обновил проверку на нулевое значение лайков 3) Обновил добавление и удаление в FilmService и InMemoryUserStorage
2) Обновил проверку на нулевое значение лайков 3) Обновил добавление и удаление в FilmService и UserController
2) Обновил проверку на нулевое значение лайков 3) Обновил добавление и удаление в User, UserService и ValidationServiceTests
2) Добавил ErrorHandler 3) Обновил UserController и FilmController
2) Добавил ErrorHandler 3) Обновил UserController и FilmController
2) Добавил ErrorHandler 3) Обновил UserController и FilmController
2) Изменил UserController для возвращения кода 404 при попытке обновить несуществующего пользователя
| } | ||
| if (films.containsKey(film.getId())) { | ||
| Film oldFilm = films.get(film.getId()); | ||
| if (!filmService.getAllMapFilms().containsKey(film.getId())) { |
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.
Код со строк 47-50 является бизнес логикой приложения, его нужно вынести на уровень сервиса
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.
Вынес на уровень сервиса бизнес логику из FilmController.
| @PutMapping | ||
| @ResponseStatus(HttpStatus.OK) | ||
| public Film updateFilm(@Valid @RequestBody Film film) { | ||
| if (film.getId() == null) { |
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.
Лучше добавить аннотацию валидации @NotNull над полем id в классе Film
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.
Убрал лишний код (при добавлении аннотации валидации @NotNull в класс Film срабатывают ошибки в прохождении POSTMAN теста.
| if (newUser.getId() == null) { | ||
| log.error("Не введен id пользователя при изменении"); | ||
| public User updateUser(@Valid @RequestBody User user) { | ||
| if (user.getId() == null) { |
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.
Нужно добавить аннотацию @NotNull над полем id класса User
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.
Убрал лишний код (при добавлении аннотации валидации @NotNull в класс User срабатывают ошибки в прохождении POSTMAN теста.
| if (user.getId() == null) { | ||
| throw new ValidationException("id пользователя должен быть указан"); | ||
| } | ||
| if (!userService.getAllUserMap().containsKey(user.getId())) { |
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.
Код со строк 40-43 нужно перенести в сервис
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.
Вынес на уровень сервиса бизнес логику из UserController.
| throw new UserNotFoundException("Пользователь с id =" + newUser.getId() + " не найден"); | ||
| @ExceptionHandler(UserNotFoundException.class) | ||
| @ResponseStatus(HttpStatus.NOT_FOUND) | ||
| public Map<String, String> handleUserNotFound(final UserNotFoundException e) { |
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.
Есть класс GlobalExceptionHandler, где отлавливаются все ошибки приложения. Данный код нужно удалить
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.
Расширил класс GlobalExceptionHandler, в котором отлавливаются ошибки приложения, убрал дубль из UserController.
| } | ||
|
|
||
| @Override | ||
| public Map<Long, Set<User>> getFriendsMap() { |
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.
Удалил лишние методы из InMemoryUserStorage.
| } | ||
|
|
||
| @Override | ||
| public void setCollectionAllUsers(Map<Long, User> allUsers1) { |
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.
Удалил лишние методы из InMemoryUserStorage.
| } | ||
|
|
||
| @Override | ||
| public Set<User> getUserFriends(long id) { |
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.
Удалил лишние методы из InMemoryUserStorage.
| } | ||
|
|
||
| @Override | ||
| public void updateUsersFriends(long id, Set<User> userSetFriends) { |
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.
Удалил лишние методы из InMemoryUserStorage.
| import static org.junit.jupiter.api.Assertions.*; | ||
|
|
||
| @SpringBootTest | ||
| public class ValidationServiceTests { |
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.
Данные тесты нужно удалить, так как они тестируют не работающую валидацию. Взамен нужно написать тесты, которые будет тестировать реальную валидацию. Как это сделать написала в комментарии к ValidationService
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.
Удалил не используемый класс ValidationService и заменил тесты на ValidationTests с проверкой валидации и ServiceTests с проверкой на работу с друзьями, с лайками, популярными фильмами.
2) Убрал лишний код (при добавлении аннотации валидации @NotNull в класс Film срабатывают ошибки в прохождении POSTMAN теста. 3) Убрал лишний код (при добавлении аннотации валидации @NotNull в класс User срабатывают ошибки в прохождении POSTMAN теста. 4) Вынес на уровень сервиса бизнес логику из UserController. 5) Расширил класс GlobalExceptionHandler, в котором отлавливаются ошибки приложения, убрал дубль из UserController. 6) Удалил лишние методы из InMemoryUserStorage. 7) Удалил не используемый класс LikeComparator. 8) Удалил лишние getFriends и setFriends из User. 9) Убрал wildcard из импортов проекта. 10) Удалил не используемый LikeComparator из FilmService. 11) Выделил в отдельный метод и переиспользовал повторяющиеся строки кода в FilmService. 12) Использовал film и filmToCompare вместо однобуквенных переменных в FilmService. 13) Переписал циклы в стиле Stream API в UserService. 14) Удалил не используемый класс ValidationService. 15) Удалил не используемый класс ValidationServicetest. 16) Создал класс Validationtest для тестирования спринговой валидации. 17) Использовал List вместо Collection в FilmStorage. 18) Сделал класс InMemoryFilmStorage final. 19) Удалил лишний метод, добавив аннотацию генерирующую конструктор для final полей класса в InMemoryFilmStorage. 20) Удалил лишние методы из InMemoryFilmStorage. 21) Сделал класс InMemoryUserStorage final. 22) Удалил лишнюю мапу из InMemoryUserStorage. 23) Удалил лишний метод, добавив аннотацию генерирующую конструктор для final полей класса в InMemoryUserStorage. 24) Удалил лишние методы из InMemoryUserStorage. 25) Использовал List вместо Collection в UserStorage.
| @GetMapping | ||
| public List<Film> findAll() { | ||
| return new ArrayList<>(films.values()); | ||
| return new ArrayList<>(filmService.getAllFilms()); |
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.
Чтобы не кастовать Collection в List, на уровне сервиса нужно возращать интерфейс List вместо Collection
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.
Заменил Collection на List в FilmService.
| log.error("Фильм с id = {} не найден", film.getId()); | ||
| throw new UserNotFoundException("Фильм с id = " + film.getId() + " не найден"); | ||
| @GetMapping("/popular") | ||
| public Collection<Film> getPopularFilms(@RequestParam(required = false, defaultValue = "10") Integer 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.
Давай здесь тоже будем возвращать пользователю List
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.
Заменил Collection на List в FilmService и FilmController.
| @GetMapping | ||
| public List<User> findAll() { | ||
| return new ArrayList<>(users.values()); | ||
| return new ArrayList<>(userService.getAllUsers()); |
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.
Нужно на уровне сервиса возвращать List вместо Collection
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.
Заменил Collection на List в UserService.
| throw new UserNotFoundException("Пользователь с id =" + newUser.getId() + " не найден"); | ||
| @GetMapping("/{id}/friends/common/{otherId}") | ||
| public List<User> getCommonFriends(@PathVariable Long id, @PathVariable Long otherId) { | ||
| return new ArrayList<>(userService.generalFriends(id, otherId)); |
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.
Замени Collection на List
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.
Заменил Collection на List в UserService
| @RestControllerAdvice | ||
| public class GlobalExceptionHandler { | ||
|
|
||
| public static class FilmNotFoundException extends RuntimeException { |
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.
Эта ошибка нигде не выбрасывается, чтобы ее отлавливать в ExceptionHandler. Данный код и код со строк 29-34 - бесполезный
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.
Удалил неиспользуемый код в GlobalExceptionHandler.
| } | ||
|
|
||
| private long getNextId() { | ||
| long currentMaxId = allUsers.keySet().stream().mapToLong(id -> id).max().orElse(0); |
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.
Стримы принято бить по строкам:
| long currentMaxId = allUsers.keySet().stream().mapToLong(id -> id).max().orElse(0); | |
| long currentMaxId = allUsers.keySet().stream() | |
| .mapToLong(id -> id) | |
| .max() | |
| .orElse(0); |
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.
Сделал стрим более читаемым.
| class FilmLikesTests { | ||
| @Test // Тесты для работы с лайками | ||
| void testLikeOperations() { | ||
| Film film = new Film(); |
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.
Вместо того, чтобы в каждом тесте создавать одинаковые объекты, их можно вынести в блок @BeforeEach и избавиться от дублирований кода
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.
Удалил дубли, вынеся их блоком @beforeeach в ServiceTests.
2) Заменил Collection на List в UserService. 3) Заменил возвращение пользователю getPopularFilms интерфейс List в FilmService. 4) Удалил неиспользуемый код в GlobalExceptionHandler. 5) Сделал стрим более читаемым. 6) Удалил дубли, вынеся их блоком @beforeeach в ServiceTests.java