27 March 2012

Me against the world: Singleton?

I just looked at http://www.reddit.com/r/java/comments/qpb8p/java_ee_revisits_the_design_patterns_singleton/. I find it rather interesting that the comments against Singleton have low scores and comments in favor have high scores.

This leads me to think: is it me against the world? Well at least my kind of programmer - that thinks that Singleton is a code smell - is in minority? Just to boost "my" side of argumentation let me be clear:

Don't us Singleton(s)!

I have personally had firsthand experience of inheriting a code base where Singletons was used extensively. It's a total nightmare! For me two areas stand out:
  • Writing test code for Singleton is much harder. You always have to watch out if one part of the code makes a side effect that makes your test case either false positive or false negative.
  • Converting a single threaded system into a multi threaded system just does not work with Singleton. You basically have to remove everything for it to work well and to avoid unnecessary synchronizations.

Easy java decompilation


Java Decompiler is a nice decompiler for Java. Lets try it! Here is my source code:
package se.lesc.blog;

/** This is class that shows how decompiled classes may look like */
public class DecompileExample {

    public static void main(String[] args) {
        
        String output = "";
        //Lets print out 10 Hello world
        for (int i = 0; i < 10; i++) {
            output += "Hello World\n";
        }
        System.out.println(output);
    }
}
When opening DecompileExample.class in Java Decompiler it looks like this;

As you can see it is very easy to browse related class files in the navigation pane to the right.When saving the source code to a file it will look like this:
/*    */ package se.lesc.blog;
/*    */ 
/*    */ import java.io.PrintStream;
/*    */ 
/*    */ public class DecompileExample
/*    */ {
/*    */   public static void main(String[] args)
/*    */   {
/*  8 */     String output = "";
/*    */ 
/* 10 */     for (int i = 0; i < 10; i++) {
/* 11 */       output = output + "Hello World\n";
/*    */     }
/* 13 */     System.out.println(output);
/*    */   }
/*    */ }

Things to note:
  1. The original line numbers has been added as a comment.
  2. Every original comment has been removed (it is removed in the compilation phase).
  3. The string operator += has been replaced by = output +.