Skip to content

Lesson 46 (lambda) for review#98

Open
Binary-Cat-01 wants to merge 3 commits intoKFalcon2022:for-prfrom
Binary-Cat-01:lesson_46_lambda_for_review
Open

Lesson 46 (lambda) for review#98
Binary-Cat-01 wants to merge 3 commits intoKFalcon2022:for-prfrom
Binary-Cat-01:lesson_46_lambda_for_review

Conversation

@Binary-Cat-01
Copy link
Copy Markdown

No description provided.


printList(cars, "Машины отсортированные по году:");

cars.sort(Comparator.comparing((Car car) -> car.getIdentifier()
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Указывать тип в лямбде можно, но не принято - это, по сути, захламление кода, которое ни на что не влияет


printList(cars, "Машины отсортированные по цвету:");

cars.sort(Car::compareTo);
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Это метод референсы и они будут чутка дальше:)

}

private static void soundAll(List<Animal> animals) {
animals.forEach(Animal::sound);
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Опять же, тут больше направленность именно на лямбды, а не референсы. Да, в конечном итоге мы придем именно к такому виду. Но пока задача стоит наиболее полно разобраться с принципами описания лямбда-выражений

@@ -0,0 +1,7 @@
package com.walking.lesson46_lambda.task3.exception;

public class UnableParsingException extends RuntimeException{
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

пробел потерял

}
}

private static void printSearchResult(List<?> results) {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

почему wildcard? тут же предопределен тип

System.out.println(result);
}

System.out.println("-".repeat(23));
Copy link
Copy Markdown
Owner

@KFalcon2022 KFalcon2022 Aug 24, 2024

Choose a reason for hiding this comment

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

сильно недокрутил декомпозицию. получается, что Main отвечает за запуск программы, инициализацию данными, меню, часть внутренней логики пунктов меню (как в случае с фильтрацией) или даже отдельных фильтров (валидация для фильтра по году). Как будто ту мач

} else {
String[] filters = Arrays.copyOfRange(arguments, 1, arguments.length);
List<CarFilter> carFilters = parseFilters(filters);
CarFilterService carFilterService = new CarFilterService(carFilters);
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Зачем на каждый вызов создавать инстанс сервисного класса? Сервисы обычно синглтоны, но, что еще важнее, они в 99% случаев - стейтлесс

@@ -0,0 +1,19 @@
package com.walking.lesson46_lambda.task3.model;

public class CarFilter {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Хорошая идея

String filterName = namesAndValues[i];
String filterValue = namesAndValues[++i];

if (filterName.equals("yearRange")) {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Нам точно нужно заставлять пользователя вводить полное название фильтра? В целом, это ок на данном этапе, иногда и в боевых задачах (от SQL до всяких QL в жира и не только), но для псевдо-gui в консольке кажется избыточным. Всегда есть варианты с нумерацией фильтров и не только.

Опциональное замечание

package com.walking.lesson46_lambda.task3.model;

public class CarFilter {
private final String name;
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Тут константный набор допустимых значений. Можно о енаме подумать

return predicate;
}

private Predicate<Car> choosePredicateBy(String name) {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

getPredicateBy


case "partOfNumber" -> getPartNumberContainsPredicate();

case "yearRange" -> getYearInRangePredicate();
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

константы. Или енам

return car -> car.getIdentifier()
.getYear() >= startInclusive && car.getIdentifier()
.getYear() <= endInclusive;
}
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

в общем виде - хорошая реализация. Отдельные детали пометил выше

public class CarService {
private final List<Car> cars = new ArrayList<>();

public CarService(Collection<? extends Car> cars) {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

зачем wildcard?

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.

2 participants