DEV Community

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

Posted on • Updated 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) {     

  //...     
  }
}