DEV Community

Cover image for Code Smell 13 - Empty Constructors
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

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.*

TL;DR: Pass the essence to all your objects so they will not need to mutate.

Problems

  • Mutability

  • Incomplete objects

  • Concurrency inconsistencies between creation and essence setting.

  • Setters

Solutions

  1. Pass the object's essence on creation

  2. 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

class AirTicket {
   constructor() {     
  }
}
Enter fullscreen mode Exit fullscreen mode

Right

class AirTicket {
   constructor(origin, destination, arline, departureTime, passenger) {     

  //...     
  }
}
Enter fullscreen mode Exit fullscreen mode

Detection

Any linter can warn this (possible) situation.

More info

%[https://codexposed.hashnode.dev/constructors-demystified]

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.

Last update: 2021/06/18

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

Top comments (0)

Dev Diairies image

User Feedback & The Pivot That Saved The Project

🔥 Check out Episode 3 of Dev Diairies, following a successful Hackathon project turned startup.

Watch full video 🎥

👋 Kindness is contagious

Sign in to DEV to enjoy its full potential—unlock a customized interface with dark mode, personal reading preferences, and more.

Okay