A Funny Java Flavoured Look at the World

Wednesday, May 10, 2006

Static classes in Java

This blog is about static code in Java and enclosing of constructor so it can never be instantiated and using what I call Static classes.  I often wanted to create classes that weren't instantiated and I wasn't sure how to do this until I read Effective Java where one of the points it talks about is that.  It still can be slightly confusing because you do still have a number of options, like Abstract classes, Singletons. 
 
I was thinking about this because sometimes need helper classes with static methods in, a class with useful methods but no variables. Often these classes are functions in one class but then I find I need that functionality in another class.  This point I consider whether or not I want that class being dependant on the class that currently holds the method.  I also consider does that class need that functionality, what is the role of that class.  When deciding things like this I try and consider the rule
 
"A class should only have one reason to change"
 
although putting useful methods in a class is probably also breaking that rule, you have to put them somewhere and I would prefer the dependency to be on the helper class rather than a class which's main job is doing something else
 
I find this helps me decide whether I should extract the function into another class. Sometimes if your classes are in a hierarchy you can pull up the method, enabling many classes below to be able to access the method.  If your classes are not in a hierarchy or if other classes not releated to the class and many other classes would like to use it but it's not really enough to make its own class.  These are the sort of naming, what package to put something in conundrums I sometimes get it and I sort of get frozen trying to think of a good name and where to put it.  What I am talking about is basically a utility or helper class, which I'm sure many of you use. 
 
So basically you want to make a helper class with a useful static standalone method which people can call if they need it.  What you don't want though is for people to instantiate this class.  There are a few options, you could make it a singleton, you could make it abstract or you could make what I call a static class.
 
The reasons why you don't want to make it abstract are because someone could subclass it.  This is probably very unlikely because everyone will know it's a helper class because you have probably called it helper or utility.  It's important to consider the design in more than just what's possible but as an intent of the use of the class.  If I see an abstract class I think it's meant to be extended, someone has designed it that way.  You also don't want people having to know you don't want them to instantiate it even thought its abstract but they should instantiate those other abstract classes because I want you to extend those. You could create a singleton, to ensure that only one object is created from the class.  Singletons are classes with a private constructor's and often with a getInstance method which has code in to this also sends out the wrong signals (for this example).  You create a singleton class (
 
here is the classic Singleton code from this good article at Java World http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns_p.html
 
public class ClassicSingleton {
   private static ClassicSingleton instance = null;

   protected ClassicSingleton() {
      // Exists only to defeat instantiation.
   }
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }
}
 
The class below is my so call static class

/**
 * A helper class with useful static utility functions.
 */
public final class ActionHelper {
 
    /**
     * private constructor to stop people instantiating it.
     */
    private ActionHelper() {
        ///this is never run
    }
 
   
    /**
     * prints hello world and then the users name
     * @param users name
     */
    public static printHelloWorld(final String name) {
         System.out.println("Hello World its " + name);
    }
      
}
 
 
So what's the difference between the two examples and why do I think the second solution is better for a class you don't want or need to instantiate.  Firstly the Singleton pattern is very useful if you want to create one instance of a class.  For my helper class we don't really want to instantiate any copy's of the class. The reason why you shouldn't use a Singleton class is because for this helper class we don't use any variables.  The singleton class would be useful if it contained a set of variables that we wanted only one set of and the methods used those variables but in our helper class we don't use any variables apart from the ones passed in (which we make final). For this reason I don't believe we want a singleton Instance because we do not want any variables and we don't want anyone instantianting this class.  So if you don't want anyone instantiating the class, which is normally if you have some kind of helper/utils class then I use the what I call the static class, a class with a private constructor and only consists of Static methods without any any variables.
 
In some ways its a bit like a web services, you just use its methods and it converts the data you give it. 
 
I'm not sure what other people think about this or how they code their helper classes, please leave some comments and let me know.
 

5 Comments:

  • The primary concern with static methods is that they cannot be overridden. Sometimes that is a Good Thing, sometimes it is a Bad Thing.

    Regardless, it's something to keep in mind when you're designing your classes.

    By Blogger Doug, at Wed May 10, 04:31:00 pm 2006  

  • the ClassicSingleton certainly is classic, it suffers from the classic double checked locking is broken problem.

    What Doug said...

    By Anonymous Anonymous, at Thu May 11, 02:05:00 am 2006  

  • Static classes are telling you that something is missing from your design. The example I use is final static java.lang.Math. This is behavior with no state, as you said a collection of functions. But if you look at *why* that class is necessary, it is because Java exposes primitives as second class entities in the language. IOWs, primitives are not objects and cannot be treated as such. But you still have to do things with them and hence you need a library. And that is when the static Math class steps in. It all goes away if int, float etc. are treated (syntaxticly) as first class citizens in the language.

    One arguement used to support the notion of primitives in Java is performance. My response is that what we have is a confusion of interface and implementation. The language maybe how we (as programmers) view things, but that view is translated by a compiler into some representation (byte code then native code). As an example, Smalltalk (the language) exposes int, float etc. as first class objects. However the runtime sees them as immediate directs. Immediate direct is the $2 word for primitive.

    The best thing to do when you see these constructs creeping into your code is to step back and ask "what am I missing ?" If you ask that simple question, what element of my design am I missing, you'll most likely find an answer that helps to clarify your work. At least it has been my experience that finding the missing design element helps to crystalize or clarify your model.

    - Kirk

    By Anonymous Anonymous, at Thu May 11, 07:10:00 am 2006  

  • Very pretty design! Keep up the good work. Thanks.
    »

    By Anonymous Anonymous, at Fri May 19, 08:54:00 am 2006  

  • Nice idea with this site its better than most of the rubbish I come across.
    »

    By Anonymous Anonymous, at Fri May 19, 07:06:00 pm 2006  

Post a Comment

<< Home