Java is an OO language, which means much of the functionality of a Java application is encapsulated into cohesive classes that can be instantiated and acted upon.
Tutorial Details:
Nevertheless, once in a while you end up with some functions that are applicable to more than one class. These functions don't really belong to any particular class, but to a sub-system or a package. Although one can express this grouping as a class by itself (represented by interfaces), it is just simpler to collect them as static functions in a class, when one doesn't need the sophistication of service-centric approach for these methods. For example, I have a class called ServletUtils (see Example 1 below).
One characteristic of static functions is that they are stateless, although for efficiency they may depend on some static variables. When these static variables are introduced or utilized, you need to know the class initialization rules laid out by the language. Although these rules are fairly intuitive, it is beneficial to know them in some depth, as static initialization involves side effects. This article is about what these side effects are and how to minimize them through a pattern called Static Resource Holder. With this in mind, I want to first review the basics of static initialization rules. For a complete treatment of the rules, refer to the Java language specification links at the end of the article.
Example 1. ServletUtils
public class ServletUtils
{
static public void
writeOutAsJavaScript(PrintWriter out,
StringBuffer javaScript);
static public String
convertToHtmlLines(String inString);
static public Map
parseQueryString(String httpQueryString);
static public Map
getParameters(HttpServletRequest request);
static public String
getSusbstitutedURL(String encodedString,
Map arguments);
//.. so on and so forth
}
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Understanding the Interplay Between Utility Classes and Static Initialization
View Tutorial: Understanding the Interplay Between Utility Classes and Static Initialization
Related
Tutorials:
|