Field initialization in Constructor
Hi
I have a Question about a Design issue.
For example, I have a class that stores a Hashtable. This Hashtable should never be null, so it is initialized. I have these two alternatives:
class Test{
Hashtable table=new Hashtable();
}
class Test{
Hashtable table;
public Test(){
this.table=new Hashtable();
}
}
So, which approach is better in what Situation? The only difference I see is, that the first example spends time for initialization on class loading, the other on instantiation. Therefore I would rather use the first one.
What suggestions do you have?
[968 byte] By [
hupfdulea] at [2007-10-2 5:21:02]

Both spend time on instantiation. You can go further and write
class Test{
Hashtable table;
protected Hashtable getTable(){
if(table == null) {
this.table= new Hashtable();
}
return table;
}
}
Denis Krukovsky
http://dotuseful.sourceforge.net/
http://dkrukovsky.blogspot.com/
Of course, if the object's hash table (you should be using HashMap, by the way) is integral to its use then the lazy approach doesn't actually help. I mean, if you're going to use it anyway...~Cheers
> So, which approach is better in what Situation? The
> only difference I see is, that the first example
> spends time for initialization on class loading, the
> other on instantiation. Therefore I would rather use
> the first one.
>
> What suggestions do you have?
Normally I would use the member initialization.
The exception to that would be if I expect that the initialization might throw an exception. In that case it is easier to control and understand the exception flow if it is generated by the constructor rather than the class load.