
patternnotes
PatternNotes provides Java annotations for design patterns and coding idioms.
These annotations are valuable for concisely expressing a developer's intentions. For example, suppose that you are maintaining a project and you encounter code like this:
``` public class Foo { ...
private Foo() {}
private static final class FooHolder {
public static final Foo INSTANCE = new Foo();
private FooHolder() {}
}
public static Foo getInstance() {
return FooHolder.INSTANCE;
}
...
} ```
You might wonder about the purpose of the nested class. You may recognize Foo
as a singleton, but the nested class gives you pause. Maybe the nested class seems extraneous at first glance, but the original writer probably had some good reason for putting it there. You certainly don't want to break anything, so it would be valuable to understand what the original author was thinking. Maybe this is some "special" form of singleton that you've not seen previously.
Now look at this annotated version:
``` @Singleton public class Foo { ...
private Foo() {}
@LazyInitializationHolder
private static final class FooHolder {
public static final Foo INSTANCE = new Foo();
private FooHolder() {}
}
public static Foo getInstance() {
return FooHolder.INSTANCE;
}
...
} ```
Now you are sure that Foo
is intended to be a singleton, as you suspected. Also, there is an annotation on the nested class. You jump to the source code of the annotation and read the annotation's Javadoc to learn that the technique is discussed in the popular Java books "Effective Java" and "Java Concurrency in Practice" and on blogs.
You consult these references and learn about the synchronization issues involved. Confident in the knowledge that you understand the situation, you make your changes while retaining existing functionality.
Copyright © 2008, Iparelan Solutions, LLC. All rights reserved.
Project Information
- License: GNU Lesser GPL
- 5 stars
- svn-based source control
Labels:
java
designpatterns
annotations
idioms