Tuesday, May 02, 2006

Default Constructor: a possible solution

I finished my last post grunting like an angry old man. Time to stop whining and start proposing something. Ok, here’s what I do. As a rule in my projects, I mark parameterless constructors in domain classes as @deprecated. This way I can monitor bad coding habits without affecting frameworks that need to access the default constructor. This normally raises questions so I have a chance to explain to developers why I consider it an anti-pattern and to find a solution (normally a robust constructor or a factory).

Another possible solution is to make it a check in source code quality checkers such as checkstyle, this approach eases the burden of manually adding the deprecation comment in all the classes, but requires the team to be familiar with the tool, while deprecation should already be in every developer’s scope.

Tags: , ,


unni vemanchery mana said...

After reading your article, I felt this way.If there is a default constructor provided, then if that class needs to be instantiated elsewhere in the application,it is very easy to do by calling new operator.It happens sometime without sense and that way so many objects dumb in the memory.But if a class without having a default costructor, then it is bit difficult to create its objects.

Alberto Brandolini said...

Hi Unni,

the problem with the default constructor is that doesn't provide any information to the class user about how the class should correctly be instantiated.

There are historical reasons why the default constructor was defined and it was a tool intended to be used by frameworks not humans.

You are pointing to a typical programmer's dilemma: "I need an instance of that class ...now!" which has a quick solution in using the first constructor available. Java is sometimes fooling the programmer, because it provides you implicitly the default constructor out-of-the-box, by relying on it you are deferring the resolution of the "What's the best way to create an instance of this class?" problem. Deferring can be acceptable in some circumstances, but needs a marker, and @deprecation fits quite well in the role. A better designed constructor (taking all mandatory fields as parameters), a Factory or a Builder are good solutions for the creation problem.