I come across few of the times called helper objects... can anybody elaborate what are those helper objects and why do we need them?
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.
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).
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.
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.
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:
static
and accessing them in a static way, like IOUtils.closeQuietly(inputStream)
closes an InputStream
wihtout throwing exceptions.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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With