GWT dropdown Fail

A colleague has asked me to post some of my own failures here. For one, because he thought it’s unfair otherwise but for second, because he found a good one. It occured when writing a straight-forward GWT mockup of some GUI which finally was deployed a couple of weeks ago.

Here is the code to initialize a dropdown with some values:

   @Override
   public void onLoad()
   {
       templatesList.clear();
       GWTClient.getServerStub().getTemplateList(new AsyncCallback<List<Template>>()
       {
           
           @Override
           public void onFailure(Throwable caught)
           {
               
               GWT.log("", caught);
           }
           
           @Override
           public void onSuccess(List<Template> result)
           {
               for (Template template : result)
               {
                   // only use enabled templates
                   if (template.getEnabled())
                   {
                       templatesList.addItem(template.getName(), template.getId().toString());
                   }
               }
           }
       });
       templatesList.setEnabled(true);
   }

And here is the code executed on selection of an entry of that dropdown:

   public void onTemplateSelection()
   {
       selectButton.setVisible(false);
       templatesList.setVisible(false);
       templatesList.setEnabled(false);
       
       GWTClient.getServerStub().getTemplateList(new AsyncCallback<List<Template>>()
       {
           
           @Override
           public void onFailure(Throwable caught)
           {
               
               GWT.log("", caught);
           }
           
           @Override
           public void onSuccess(List<Template> result)
           {
               Template template = result.get(templatesList.getSelectedIndex());
               templatePanel.init(template);
               rootPanel.add(templatePanel);
               rootPanel.add(buttonBar);
           }
       });
       
   }

I guess I got lazy when I realized I had to cast the ID from String to Integer again in order to make it right. Bad choice. Probably the enabled-property came into that code later than the dropdown. Here you see what you get from laziness – your code stinks.

The code seemed to work quite fine until someone actually used the enabled-property on those templates. The dropdown still looked alright…

Naming Fail

I’ve no idea what went wrong here. Nice, clean code. Javadoc is present. Completely useless.

/**
* Interface for switchable artefacts
*/
public interface Switchable
{
        /**
        * set the component on or off
        */
        public void setOnOrOff(boolean value);
        
        /**
        * returns if the artefact is on or off
        */
        public boolean getOnOrOff();
}

More Enumeration Fail

I recently came across of some brilliant chunk of WTF-code. The reason was that some swedish users complained about the software not caring about their language settings.

First step was to review the method which stored the settings:

public class DBwriter extends DBaccess {

    public enum Lang {
	DE, EN, FR, NL, SV, IT;
    }

    public void saveLangSetting(long userId, Lang lang) {
	super.executePreparedStatement("INSERT INTO usersettings VALUES ('?','?')", userId,lang.name());
    }
}

Second step was the method which fetched the stored settings:

public class DBreader extends DBaccess {

    public enum Lang {
	DE, EN, FR, NL, ES, IT;
    }

    public Lang getUserLang(long userId) {

	Lang res = Lang.EN;
	try {
	    res = Lang.valueOf(super.executePreparedStatement("SELECT * from usersettings WHERE id=?", userId).getString("lang"));
	} catch (Exception e) {
	    // why should this happen?
	}
	return res;
    }
}

It was a famous moment to realize what was happening there. But it even got better in the moment I found the only usage of getUserLang:

Lang lang = reader.getUserLang(id);
session.setLanguage(lang.name());

I’m just proud the thousand monkeys on their thousand typewriters somehow managed to store some languages successfully.

Enumeration Fail

The more I dig into some older code lately the more I wonder what my colleague was drinking all the time.

/**
* Enumeration of Names
*/
public interface Names
{
	static final public String NAME_1 = "ONE";
	static final public String NAME_2 = "TWO";
	static final public String NAME_3 = "THREE";
}

Why not. But at least he could have the javadoc fixed.

Java Singelton fail

Exciting WTF moments at work (no joke, stuff I’ve seen coded by real Java professionals):

public static ThisObject getInstance(){
   return this.instance;
}

So far, so good. Looks like a normal singelton pattern.

public static void setInstance(ThisObject object){
    this.instance=object;
}

This seems to be a little odd. But ok, I’ve seen this before for smuggling Mock-Instances during jUnit-Test into the otherwise static-referenced Singleton. Not nice but quite applicable when Unit-Tests are created for code fragments using this singleton.

public static ThisObject createInstance(){
    return new ThisObject();
}

This code really caused some raising eyebrows. Turns out that someone reused some methods in a kind of stateless way, which where supposed to work only statefully within the instance of the singleton. So he created this little factory method which always created unused instances. This actually worked because no static fields were accessed within the methods.

public static void killInstance(){
    this.instance = null;
}

Code actually used with a lazyloading singleton pattern. Actually this was proven to be working code. Think about it. Twice.

The philosophy of a prototype

Prototypes are something every software developer comes across in his lifetime. Usually quite informal in the early stages of their career by coding by the trail-and-error-pattern where every iteration can be seen as a prototype for the next. Later on, with projects getting bigger, it is most likely that the programmer starts to use prototypes more systematically. Some even learn to formalize them and use them in a professional way. In the end, software developers can be categorized in two groups:

  1. Those who see prototypes as a build-product in early stages of software development which improves project quality and resource planning by testing certain aspects and/or try new methods to create the product and which must be thrown away before the actual project is started to reach best possible product quality
  2. Those who do not care so much about all these words and just like to code straight away

From how I wrote this, you might get an idea which philosophy of those both I personally prefer. But I’m not one of those who take the proceeding too seriously. I regard the prototype as a piece of software which I use to analyze and gain information to compensate missing knowledge. This might be because I want to learn about a new technology or because I want to try new tools. Or because I never worked on a similar project before – which should be quite usual for a ambitious software developer. But I do not regard it necessary to create a prototype for really every project I work on. Sometimes it is possible to just determine one.

As the experience of the engineer increases, it is sometimes possible to find old projects which just can be looked at from another new point at view. Or it is possible to find another project which fulfills similar aspects to what one intends to work on. This approach however requires a highly skilled engineer as it is a difficult task to gain knowledge from a foreign codebase. Especially if the requirements or the design of the foreign project was not documented. This is sadly quite often the case in available open-source projects. In this case the gain of knowledge is close to zero.