Code Smell 13 - Empty Constructors
No-Parameterized constructors are a code smell of an invalid object that will dangerously mutate. Incomplete objects cause lots of issues.
Problems
Mutability
Incomplete objects
Concurrency inconsistencies between creation and essence setting.
Setters
Solutions
Pass the object's essence on creation
Create objects with their immutable essence.
Examples
- Some persistence frameworks in static typed languages require an empty constructor.
Exceptions
- Stateless objects. Always better solution than static class methods.
Sample Code
Wrong
Right
Detection
Any linter can warn this (possible) situation.
More info
Tags
Essence
Incomplete
Mutable
Conclusion
Always create complete objects. Make their essence immutable to endure through time.
Every object needs its essence to be a valid one since inception.
We should read Plato's ideas about immutability and create entities in a complete and immutable way.
These immutable objects favor bijection and survive the passing of time.
Credits
Photo by Brett Jordan in Pexels
In a purely functional program, the value of a [constant] never changes, and yet, it changes all the time! A paradox!
Joel Spolski
This article is part of the CodeSmell Series.
Software Engineer
Fair point. While I can't agree that it's an universal rule of thumb, objects are there to be self-explanatory.
As example, you may find constructor to be unnecessary in writing classes that extend Cog
from discord.py library with arbitrary methods, and yet extended class has everything needed for setup.
Actually, since these library conventions make me write less boilerplate code and have everything needed in parent constructor, rule in this article just should be enforced on pure classes. (Just a note for myself.)
Comments (2)