Video in progress
What does it mean when a method takes 6-7 parameters, and how do you fix it?
This is the "long parameter list" smell: at the call site the parameters are easy to mix up, and often several of them are really one concept. You need to gather them into a parameter object or a value object, or split the method.
📖 Answer
List<Order> search(LocalDate from, LocalDate to, String status,
Long customerId, int page, int size, String sort) { ... }
search(to, from, "PAID", 15L, 0, 20, "createdAt"); // from and to got swapped, and the compiler says nothing
Adjacent parameters of the same type are the most dangerous. A bug like this doesn't show up in review either.
The fix is grouping:
record DateRange(LocalDate from, LocalDate to) {
DateRange {
if (from.isAfter(to)) throw new IllegalArgumentException("from > to");
}
}
record OrderFilter(DateRange period, OrderStatus status, Long customerId) {}
Page<Order> search(OrderFilter filter, Pageable pageable);
What changed:
DateRangechecks its own rule and can be used in other places too;statusis now an enum, not aString;- for paging we use Spring's ready-made
Pageable.
There can be another reason: the method does too much and the parameters belong to different jobs. In that case, splitting the method is the right way.
If a constructor has many parameters, look at a builder or static factories. But if a bean constructor has 7 dependencies, that is a different signal: the class may be violating SRP.
Sign up to mark studied questions and save your progress.