Some operations which are common to a couple of classes can be moved to helper classes, which are then used via object composition:
public class OrderService {
private PriceHelper priceHelper = new PriceHelper();
public double calculateOrderPrice(order) {
double price = 0;
for (Item item : order.getItems()) {
double += priceHelper.calculatePrice(item.getProduct());
}
}
}
public class ProductService {
private PriceHelper priceHelper = new PriceHelper();
public double getProductPrice(Product product) {
return priceHelper.calculatePrice(product);
}
}
Using helper classes can be done in multiple ways:
- Instantiating them directly (as above)
- via dependency injection
- by making their methods
static
and accessing them in a static way, likeIOUtils.closeQuietly(inputStream)
closes anInputStream
wihtout throwing exceptions. - at least my convention is to name classes with only static methods and not dependencies
XUtils
, and classees that in turn have dependencies / need to be managed by a DI containerXHelper
(The example above is just a sample – it shouldn’t be discussed in terms of Domain Driven Design)