Static Abuse
 
I just finished an end-of-the semester marathon session of grading programs. I noticed a number of students that misuse static method and static fields. To help illustrate I will use a Stack class.
 
class Stack {
    private ArrayList elements = new ArrayList();
 
    public void push(Object element) {
        elements.add(element);
    }
 
    public Object pop() {
        return elements.remove(elements.size() -1);
    }
}
 
On rare occasions I will come across a student that tests the code using main. They write:
 
class Stack {
    private ArrayList elements = new ArrayList();
 
    public void push(Object element) {
        elements.add(element);
    }
 
    public Object pop() {
        return elements.remove(elements.size() -1);
    }
 
    public static void main(String[] args) {
        push("cat");
        System.out.println(pop()):
}
 
Of course the compiler complains about and they then "fix" the problem by making everything static:
 
class Stack {
    private static ArrayList elements = new ArrayList();
 
    public static void push(Object element) {
        elements.add(element);
    }
 
    public static Object pop() {
        return elements.remove(elements.size() -1);
    }
 
    public static void main(String[] args) {
        push("cat");
        System.out.println(pop()):
}
 
Hopefully you are shaking your head at this and wondering what the student was thinking.
 
More commonly students make all fields and methods static because they:
 
  1. 1.Think they only need one instance of the class
  2. 2.Want a easy way to provide global access to that instance
 
The students assumptions are frequently wrong. The test cases they use only need one instance at a time of the class but there are times when the program will need multiple instance of the class. The use of the static fields introduces errors into their code, which they are not aware of. If they are lucky I will catch the error and they will lose points on their assignment. They are often wrong about the need for a global access to the one instance of the class. Sometimes here is a way to provide the needed access in the program and they are just being lazy. Other times there are design problems in their code, which they get around using static methods.
 
So students when you start to use static method stop and think about what you are doing. Do you really need the global access? If so investigate the singleton pattern. Are you just trying to find a home for a bunch of functions? If so look at your classes and ask yourself why you don't have a class where the functions belong as methods.
Monday, May 21, 2007