giri giri - 3 months ago 13
Java Question

What are helper objects in java?

I come across few of the times called helper objects... can anybody elaborate what are those helper objects and why do we need them?


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)