Monday, August 31, 2009

Careful with that axe^H^H^H static, Eugene!

557403262_2d8d8a3576_b An other instance from the “bugs which will bite you” series:

public class TestStatic {
	static class Foo {
		static Foo instance = new Foo();
		static String name = Foo.class.getName();
		
		public Foo() {
			System.err.println("Hello, my name is " + name);
		}
	}
	
	public static void main(String[] args) {
		System.err.println("Your name is what?\n"
			+ "Your name is who?\n");
		
		new Foo();
	}

}

Can you spot the bug? Hint, here is the output:

Your name is what?
Your name is who?

Hello, my name is null
Hello, my name is TestStatic$Foo

A final hint: here is what FindBugs reports on the third line: SI_INSTANCE_BEFORE_FINALS_ASSIGNED

Yet an other reason to reduce your FindBugs count to zero before releasing software!

Picture taken from helena.40proof's photostream with permission.

No comments:

Post a Comment