DEV Community

Cover image for Code Smell 131 - Zero Argument Constructor
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

8 1

Code Smell 131 - Zero Argument Constructor

Objects created without arguments are often mutable and erratic

TL;DR: Pass all your essential arguments when creating objects.

Problems

Solutions

  1. Use one complete and single constructor.

  2. Avoid Setters and Getters

Context

It is common usage using a zero-argument constructor and a bunch of setters to change it.

Beans is a well-known example of this code smell.

Sample Code

Wrong

 public Person();

// Anemic and mutable
Enter fullscreen mode Exit fullscreen mode

Right

public Person(String name, int age){
     this.name = name;
     this.age = age;
     } 
 }

// We 'pass' the essence to the object 
// So it does not mutate
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

We can check all constructors, but there are some false positives.

Stateless objects are a valid example.

Tags

  • Mutability

Conclusion

Empty constructors are mutability hints and accidental implementation issues.

We need to research usages to improve our solutions.

Relations

More Info

Credits

Photo by Ade Adebowale on Unsplash


Don't worry about design, if you listen to your code a good design will appear...Listen to the technical people. If they are complaining about the difficulty of making changes, then take such complaints seriously and give them time to fix things.

Martin Fowler


This article is part of the CodeSmell Series.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay