Static Dangers


Using statics inappropriately can create significant defects that can be difficult to resolve. A classic novice mistake is to declare attributes as class variables instead of instance variables.

The class Student defines an instance variable named name. Each Student object should have its own copy of name. By declaring name as static, every Student object will use the same copy of name:

 package sis.studentinfo; public class Student {    private static String name;    public Student(String name) {       this.name = name;    }    public String getName() {       return name;    } } 

A test can demonstrate the devastating effect this will have on your code:

 package sis.studentinfo; import junit.framework.*; public class StudentTest extends TestCase {    ...    public void testBadStatic() {       Student studentA = new Student("a");       assertEquals("a", studentA.getName());       Student studentB = new Student("b");       assertEquals("b", studentB.getName());       assertEquals("a", studentA.getName());    } } 

The last assertEquals statement will fail, since both studentA and studentB share the class variable name. In all likelihood, other test methods will fail as well.

A mistake like this can waste a lot of your time, especially if you don't have good unit tests. Developers often figure that something as simple as a variable declaration cannot be broken, so the variable declarations are often the last place they look when there are problems.

Revert the Student class to eliminate the keyword static, remove testBad-Static, recompile, and retest.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net