Thursday, September 8, 2011

What is and WHAT SHOULD NEVER BE!

Is quite late now, I'm sitting in a silent room of the public library near my home. A few minutes ago I was reading a bit about Taxonomy Expansion but I got bored :-s. As I always say, I live like a rock star, so to wake me up a little bit I began to look at the source code of the application I'm supposed to maintain.Yes!, Jagger must be so jealous of me!

At the precise moment I was reading the classes of the DB module, the song "What is and what should never be" of Led Zeppelin (2nd song, disk 2, album: How The West Was Won, 1972) started to sound in my computer. I believe it was a message from God because I inmediatly found something like this:


public class BaseHandler
{
    public BaseHandler(Command command)
    {
        command.addContext(this); // WHAT IS, BUT SHOULD NEVER BE!!!!
    }
    ....
}

And this is incredible because after looking and analyzing that class the song changed (1st song, disk 2, album: How The West Was Won, 1972), the title ... "Dazed and Confused", that's exactly how I felt. It was like the rock gods Robert Plant and Jimmy Page where talking directly to me!.

Let's leave the drugs for a moment :-) ....What is the main problem of the class?. Well, "this" is not fully created, check this short example (try to run it, it prints "null"):

public class BaseHandler
{
    public BaseHandler(Command command)
    {
        command.addContext(this);  // the instance is not fully created!!!!
    }

    public void doSomething()
    {
        System.out.println("Im Base Handler");
    }
}

public class Command
{
    public void addContext(BaseHandler handler)
    {
        handler.doSomething();
    }
}

public class Handler extends BaseHandler
{
    private String message;

    public Handler(Command command, String message)
    {
        super(command);
        this.message = message;
    }

    @Override
    public void doSomething()
    {
        System.out.println(message);
    }

    public static void main(String [] args)
    {
        Handler handler = new Handler(new Command(), "Im Handler not  Base Handler");
    }
}


This is not obiously the code was looking at, it was more complex and fortunately didn't fail (no attribute was used from the constructor), but it is a good example of java class initalization. (Before a class or interface is initialized, its direct superclass must be initialized, but interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized.)

Moby dick is sounding now, I'm moving my feet as an epileptic drummer, beliving that I'm so great that I can follow the rithm (yeah! in my dreams!). Everyone have already left the room by now, I think they
are about to close the doors so I should be running out.

Have a great night!

No comments:

Post a Comment