Code Smell 15 - Missed Preconditions

Subscribe to my newsletter and never miss my upcoming articles

Assertions, Preconditions, Postconditions and invariants are our allies to avoid invalid objects. Avoiding them leads to hard-to-find errors.

Problems

  • Consistency
  • Contract breaking
  • Hard to debug
  • Bad cohesion

Solutions

  • Create strong preconditions
  • Raise exceptions
  • Fail Fast
  • Defensive Programming

Examples

  • Constructors are an excellent first line of defense

  • Anemic Objects lack these rules.

Sample Code

Wrong

Detection

  • It's difficult to find missing preconditions, as long with assertions and invariants.

Tags

  • Consistency

Conclusion

Always be explicit on object integrity.

Turn on production assertions.

Even if it brings performance penalties.

Data and object corruption is harder to find.

Fail fast is a blessing.

More info

Relations

Credits

Photo by Jonathan Chng on Unsplash


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


This article is part of the CodeSmell Series.

No Comments Yet