Default Singleton Boilerplate code in IDEA ...

While I was getting used to IDEA IntelliJ IDE, one "feature" caught my attention. They have a way to create a "Singleton" by way of a pop-up menu. Here is the code that generates the class for this controversial and damned pattern (now that Google has a Singleton Detector :-) ).
public class Single {
    private static Single ourInstance = new Single();

    public static Single getInstance() {
        return ourInstance;
    }

    private Single() {
    }
}
I see at least two problems with this "default" code:
  1. The class should have been declared final.
  2. The variable ourInstance should have been declared final.
  3. Motivation:

    Quality criterion for boilerplate code is same as that for real code (in these days of fast search engines :) ). Also, I am mildly surprised that it takes a lot of time for me to:
    • Create a Java Interface
    • Create a Class that implements that Interface with stubbed implementation for interface methods .
    This is true with both NetBeans 6.0 (which means it is true with any other IDE because NetBeans is the only IDE you need, these days :) ) and IDEA 7.0.
Comments:

Yes, and the instance variable should be named in ALL_CAPS once declared final.

Posted by Jeremy Weiskotten on December 17, 2007 at 06:20 AM PST #

I think we must also declare the method getInstance() as synchronized which ensures that the singleton property of the class is taken cae of in a multi threaded environment.

Posted by Abir Mondal on May 22, 2008 at 06:05 PM PDT #

Abir,

No, it is not required in this particular case as the class initialization guarantees that there will be exactly one instance of this class in the system. It's also immune to serialization mysteries because this class does not implement java.io.Serializable.

The keyword synchronized would be required if the class variable were not initialized.

Posted by Kedar on May 23, 2008 at 01:02 AM PDT #

I just discovered this template in IDEA, too. And I'm surprised that
a) IDEA provides a shortcut for such a controversial pattern at all
b) The code created is basically flawed

I just started working again with IDEA (after a pause of maybe 6 years) and I'm annoyed that there a such flaws in it while everyone usually only talks with high respect about IDEA.

Posted by Christoph on May 23, 2008 at 10:48 PM PDT #

Bad news is that this problem is still not fixed, but the good news is that you can modify the templates by yourself (including adding new one.) Settings > File Templates.

Posted by Kohsuke Kawaguchi on April 06, 2009 at 02:06 AM PDT #

Post a Comment:
Comments are closed for this entry.
About

Welcome to my blog where mostly my work related thoughts are expressed.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today