Object construction

Did you read “Effective Java”? If you didn’t, you should: it is one of the greatest book about java i have read so far. The only problem with this book is that – over time – you tend to forget some of the invaluable advices, you get from it.
At least, this happened to me: I wrote some Abstract a few weeks ago, that used some template Methods to delegate to its implementations, little less obvious, but essentially just like this:

                    public abstract class AbstractFoo{
  protected AbstractFoo()
  {
     initialize();
  }
  // can be used to initially read state.
  protected void initialize(){}
                

Already know what kind of trouble i was going to face? Lucky you

Few weeks later, i added an implementation to the codebase, that used some File Object:

                    public class FileFoo extends AbstractFoo{
        private File file;
  protected FileFoo(File file)
  {
     super();
     this.file=file;
  }
                

I remembered, that for the reason of initialization, i already added a method i could use, to read from that file. So i made use of that:

                   protected initialize()
  {
    readFromFile(file);
    [...]
  }
                

I guess, you see the trouble here, don’t you? The member

file

is not yet initialized, when calling the method.

Do not use non-final methods during object construction

Even worse: i added a template method, that encourages to be overwritten. Stupid me.
That’s what i call a bug pattern

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>