Skip to content

Conversation

@andrej1307
Copy link
Owner

Спринт №11 итоговый проект.

@Service
public class UserService {

protected static UserStorage users = Storages.getUerStorage();

Choose a reason for hiding this comment

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

Не стоит вручную создавать объекты, Spring сам умеет внедрять необходимые зависимости

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправлено.

*/
public User updateUser(User updUser) {
Integer id = updUser.getId();
User user = new User(users.getUserById(id));

Choose a reason for hiding this comment

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

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

Copy link
Owner Author

Choose a reason for hiding this comment

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

Убрал копирование при обновлении. Получается, что исправляем сразу объект в хранилище (даже put(...) не нужен).

public class FilmController {

@Autowired
FilmService service;

Choose a reason for hiding this comment

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

Можно сделать private final

Copy link
Owner Author

Choose a reason for hiding this comment

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

исправлено.

public class UserController {

@Autowired
UserService service;

Choose a reason for hiding this comment

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

Также можно сделать private final

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправлено.


public Collection<Film> findPopularFilms(int count) {
List<Film> popularFilms = new ArrayList<>();
popularFilms = films.findAllFilms().stream()

Choose a reason for hiding this comment

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

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

Copy link
Owner Author

Choose a reason for hiding this comment

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

Реализовал обновляемый рейтинг в хранилище и выдачу заданного числа самых популярных фильмов.

*/
public T addNew(T element) throws ValidationException {
// Проверяем существование полльзователя для исключения дублирования
if (storage.containsValue(element)) {

Choose a reason for hiding this comment

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

(Предложение)По идее, проверка должна происходить на уровне сервиса через Storage отдельным методом. Методы в хранилище должны быть простыми и работать с уже готовыми данными

Copy link
Owner Author

Choose a reason for hiding this comment

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

Перенес проверки в сервис.


Integer id = element.getId();
// проверяем необходимые условия
if (!storage.containsKey(id)) {

Choose a reason for hiding this comment

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

(Предложение) Аналогично, было бы логичнее проверку на наличие вынести в сервис

Copy link
Owner Author

Choose a reason for hiding this comment

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

Перенес проверки в сервис.

/**
* Утилитарный класс для определения реализаций хранилищ данных
*/
public final class Storages {

Choose a reason for hiding this comment

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

Фабрика в данном проекте особа не нужна, Spring сам управляет бинами

Copy link
Owner Author

Choose a reason for hiding this comment

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

Удалил классы: Storages.java, StorageData, InMemoryAbstractStorage.java

Copy link
Owner Author

Choose a reason for hiding this comment

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

StorageData.java пришлось восстановить, так как в противном случае Lombok менял число аргументов в стандартных конструкторах классов модели ..

@andrej1307 andrej1307 merged commit 9a24624 into main Jan 5, 2025
2 checks passed
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