I come across few of the times called helper objects... can anybody elaborate what are those helper objects and why do we need them?
You can see a helper class as a toolbox that can be used by other classes to perform task like testing if a string is a palindrome, if a given number is prime, if an array contains negative number etc. You can create helper class by making all its methods static and its constructor private, and optionally you can also make the class final. Thus it can not be instantiated and one can easily access to all its methods directly.
public final class HelperClass{
private HelperClass(){
}
public static boolean isPositive(int number) {
if (number >= 0)
return true;
else
return false;
}
}
Here the function can be use directly to test a number :
HelperClass.isPositive(5);
Helper class, in my opinion, is similar to normal functions declared outside of classes in C++. For example, if you need a global constant for many classes, then you can define a helper class that encloses a final static const variable.
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)
These are objects that "sit to the side" of the main body of code, and do some of the work for the object. They "help" the object to do it's job.
As an example, many people have a Closer helper object. This will take various closeable objects, for example, java.sql.Statement, java.sql.Connection, etc and will close the object, and ignore any errors that come out of it. This tends to be because if you get an error closing an object, there is not much you can do about it anyway, so people just ignore it.
Rather than having this boilerplate:
try {
connection.close();
} catch (SQLException e) {
// just ignore… what can you do when you can't close the connection?
log.warn("couldn't close connection", e);
}
scattered around the codebase, they simply call:
Closer.close(connection);
instead. For example, look at guava closeQuietly.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Helpers {
public static String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
return dateFormat.format(new Date());
}
public static boolean isTimeABeforeTimeB(String timeA, String timeB) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
Date dA = dateFormat.parse(timeA);
Date dB = dateFormat.parse(timeB);
if (dA.getTime() < dB.getTime()) {
return true;
} else {
return false;
}
} catch (Exception e) {
//
}
return false;
}
public static String getDateAndTimeInput(String prompt) {
Scanner input = new Scanner(System.in);
String ans;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
dateFormat.setLenient(false);
boolean dateValid;
do {
System.out.print(prompt);
ans = input.nextLine();
ans = ans.trim();
dateValid = true;
try {
Date d = dateFormat.parse(ans);
} catch (Exception e) {
dateValid = false;
}
} while (!dateValid);
return ans;
}
public static String getStringInput(String prompt) {
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print(prompt);
ans = input.nextLine();
ans = ans.trim();
} while (ans.length() == 0);
return ans;
}
public static double getDoubleInput(String prompt) {
Scanner input = new Scanner(System.in);
double ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
//Convert string input to integer
try {
ans = Double.parseDouble(s);
inputValid = true;
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
public static int getIntegerInput(String prompt) {
Scanner input = new Scanner(System.in);
int ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
// Convert string input to integer
try {
ans = Integer.parseInt(s);
inputValid = true;
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
public static int getIntegerInput(String prompt, int lowerBound, int upperBound) {
Scanner input = new Scanner(System.in);
int ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
// Convert string input to integer
try {
ans = Integer.parseInt(s);
if (ans >= lowerBound && ans <= upperBound) {
inputValid = true;
} else {
inputValid = false;
}
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
}
that is an example of of a Helper Class. It contains method which of are common use of the other classes in the project.
Example if someone wants to enter an Integer number from a class hew ill have to type in this: String num = Helpers.getIntegerInput("input your number");
The prompt is the output that is show to the user. Other examples to input a String, double, date and time etc.
A 'helper' method is typically a method to make something easier, whatever it is. Sometimes they're used to make things more readable/clearly organized (some may argue this, but it's ultimately very subjective):
public void doStuff() {
wakeUp();
drinkCoffee();
drive();
work();
goHome();
}
Where, each 'helper method' on their own are fairly complex... the concept becomes really clear and simple.
Another very good use of helper methods is to provide common functionality across many different classes. The best example of this is the Math
class which contains a ton of static helper methods to help you calculate things like the log of a number, the exponent of a number... etc.
Where you draw the line as to what's a helper method and what's just a regular method is pretty subjective, but that's the gist of it. Other answers here are pretty good too.