Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are helper objects in java?

Tags:

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?

like image 244
giri Avatar asked Jan 25 '10 21:01

giri


People also ask

What is helper objects in Java?

A helper class serve the following purposes. Provides common methods which are required by multiple classes in the project. Helper methods are generally public and static so that these can be invoked independently. Each methods of a helper class should work independent of other methods of same class.

What are helper objects?

In object-oriented programming, a helper class is used to assist in providing some functionality, which isn't the main goal of the application or class in which it is used. An instance of a helper class is called a helper object (for example, in the delegation pattern).

What is the difference between Util and helper?

A Utility class is understood to only have static methods and be stateless. You would not create an instance of such a class. A Helper can be a utility class or it can be stateful or require an instance be created. Create Utility class if you want to have methods that are used by several operations.

What is a purpose of a helper method?

A helper method is a small utility function that can be used to extract logic from views and controllers, keeping them lean. Views should never have logic because they're meant to display HTML.


1 Answers

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)

like image 149
Bozho Avatar answered Oct 07 '22 05:10

Bozho