What are helper objects in java?

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, like IOUtils.closeQuietly(inputStream) closes an InputStream 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 container XHelper

(The example above is just a sample – it shouldn’t be discussed in terms of Domain Driven Design)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)