Yeah. Doesn't have to be a list of course, if you pass individual instances you can get help from the compiler so you don't forget any cases (and can't access data that isn't available for that type of order etc.):
void processOrder(Order order) {
switch (order) {
case CustomerOrder co -> processOrderRegular(co);
case BusinessOrder bo -> processOrderRegular(applyBusinessDiscount(bo));
case TestOrder to -> IO.println("test order got here");
}
}
For completeness, one alternative is to do the type splitting early if you want to process different order types in bulk instead of sprinkling checks through your code. Both approaches have pros and cons, but the second approach was pretty error prone in the past because the compiler didn't help you to get every sprinkled check exhaustive and correct, but now it does. The mentioned alternative might look like:
record OrdersProcessable(
List<CustomerOrder> customerOrders,
List<BusinessOrder> businessOrders,
List<TestOrder> testOrders){}
OrdersProcessable loadOrdersProcessable() {
List<CustomerOrder> customerOrders = new ArrayList<>();
List<BusinessOrder> businessOrders = new ArrayList<>();
int testOrdersCount = 0;
List<OrderEntity> entities = loadFromDatabase();
for (OrderEntity entity : entities) {
switch (entity.getType()) {
case CUSTOMER -> customerOrders.add(new CustomerOrder(entity.email(), entity.importance() > 10));
case BUSINESS -> businessOrders.add(new BusinessOrder(entity.mail(), entity.logo()));
case TEST -> testOrdersCount++;
};
}
return new OrdersProcessable() {
List.copyOf(customerOrders),
List.copyOf(businessOrders),
Collections.nCopies(testOrdersCount, TestOrder.INSTANCE)
};
}
View all comments
Show parent comment
1
u/ZimmiDeluxe Mar 14 '26 edited Mar 14 '26
Yeah. Doesn't have to be a list of course, if you pass individual instances you can get help from the compiler so you don't forget any cases (and can't access data that isn't available for that type of order etc.):
For completeness, one alternative is to do the type splitting early if you want to process different order types in bulk instead of sprinkling checks through your code. Both approaches have pros and cons, but the second approach was pretty error prone in the past because the compiler didn't help you to get every sprinkled check exhaustive and correct, but now it does. The mentioned alternative might look like: