Code Smell 13 — Empty Constructors

Maximiliano Contieri
Dev Genius
Published in
Nov 1, 2020

--

Incomplete objects cause lots of issues.

Photo by Brett Jordan in Pexels

Problems

  • Mutability
  • Incomplete objects
  • Concurrency inconsistencies between creation and essence setting.
  • Setters

Solutions

  • Pass the object’s essence on creation

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.

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.

Writing a class without its contract would be similar to producing an engineering component (electrical circuit, VLSI (Very Large Scale Integration) chip, bridge, engine…) without a spec. No professional engineer would even consider the idea.

Bertrand Meyer

--

--

I’m a senior software engineer specialized in declarative designs. S.O.L.I.D. and agile methodologies fan. Maximilianocontieri.com