Java Pet Peeves #1:Pointless Constructors
So I was looking through some code (the author shall remain nameless :)) and spotted a shed load of my number #1 pet peeve; useless constructors:
public class Something {
public void aMethod() {
…
}
}
In the above circumstance there is absolutely no point (as far as the JRE is concerned) to put a default constructor. The following will result in exactly the same byte code (I imagine; I cannot verify this :)):
public class Something {
public Something() {
super();
}
public void aMethod() {
…
}
}
or even worse:
public class Something {
public class Something() {
}
public void aMethod() {
…
}
}
Why, oh why must people do it?
Admittedly; stupidly Eclipse provides a default constructor (with the super() call) by default, but that is no excuse.
It is quite simple; if you have no constructors, the JDK will provide a default constructor which contains a call to super() for you. You must provide a constructor if either you do not wish to have a default constructor, or the super class does not include one.
For example, if you have a class which requires a number of collaborators to work, then you should create a constructor which takes in those collaborators. Because you have provided a constructor, the JDK won't put a default one in for you, so:
public class Something {
public Something(final String s) {
}
public void aMethod() {
…
}
}
can be instantiated with:
new Something("ssss"); // good
new Something(); // bad
The JDK cannot create a default constructor if the super class doesn't itself contain a default constructor:
public class BaseClass {
}
public class ExtendedClass extends BaseClass {
// no need to put a constructor
}
public class BaseClass {
public BaseClass() {
// stupid, but used for illustrative purposes.
}
}
public class ExtendedClass extends BaseClass {
// still no need to put a constructor
}
however:
public class BaseClass {
public BaseClass(final String s) {
}
}
public class ExtendedClass extends BaseClass {
// absolutely must put a constructor in, even if it is a no-args constructor
public ExtendedClass() {
super("some value");
}
}
So please; when you create the next class, ask yourself whether it requires any collaborators, if it does, provide a single constructor with those collaborators (which should be marked final BTW :)). If it doesn't, don't provide any constructors; let the JDK do it's job.
And if you must provide a constructor; make sure you call super(...) :)
Please, for my sanity :)
And yes, before any one comments; I am guilty of this :)
06 Feb 2006, 11:11
WiB
Umm… stupid respond… but I thought hibernate requires default empty constructor?
17 Jul 2007, 04:12
Add a comment
You are not allowed to comment on this entry as it has restricted commenting permissions.