A utility class is an efficient way of allowing you to create methods that you often reuse in your code. If you find yourself using the same code over and over, and it doesn't depend on an instance variable, you can put that code in a method within a Utility class and call the method from there.
A Utility class should only contain static variables. With the class being final, these variables are effectively constants.
Important points about Utility classes
A Utility class should be final, indicating that it cannot be extended.
A Utility class should contain a private constructor, indicating that it cannot be constructed.
A Utility class should only contain final static fields. These fields are effectively constants.
A Utility class should only contain static methods. Why? Other than obvious reasons such as not being required to create an instance of the Utility class, a static method causes less overhead because of the fact that it is executed at compile-time.
Example:
public final class Utility {
private Utility() { } //Prevent the class from being constructed
/**
* Check string is null or empty.
* @param string String
* @return boolean result
*/
public static boolean isStringNullEmpty(String string){
return string==null||"".equals(string.trim());
}
/**
* Check string is not null or empty.
* @param string String
* @return boolean result
*/
public static boolean isStringNotNullEmpty(String string){
return !isStringNullEmpty(string);
}
}
No comments:
Post a Comment