Assertions, Preconditions, Postconditions and invariants are our allies to avoid invalid objects. Avoiding them leads to hard-to-find errors.
TL;DR: If you turn off your assertions just in production your phone will ring at late hours.
Problems
- Consistency
- Contract breaking
- Hard debugging
- Late failures
- Bad cohesion
Solutions
- Create strong preconditions
- Raise exceptions
- Use Fail-Fast principle
- Defensive Programming
- Enforce object invariants
- Avoid anemic models
Refactorings ⚙️
https://maximilianocontieri.com/refactoring-016-build-with-the-essence
https://maximilianocontieri.com/refactoring-035-separate-exception-types
Examples
Context
You often assume that "someone else" checked the objects before it reached your function.
This assumption is a trap. When you create objects without enforcing their internal rules, you create "Ghost Constraints."
These are rules that exist in your mind but not in the code.
If you allow a "User" object to exist without an email or a "Transaction" to have a negative amount, you create a time bomb.
The error won't happen when you create the object; it will happen much later when you try to use it.
This makes finding the root cause very difficult.
You must ensure that once you create an object, it remains valid from the very birth throughout its entire lifecycle.
Sample Code
Wrong
class Date:
def __init__(self, day, month, year):
self.day = day
self.month = month
self.year = year
def setMonth(self, month):
self.month = month
startDate = Date(3, 11, 2020)
# OK
startDate = Date(31, 11, 2020)
# Should fail
startDate.setMonth(13)
# Should fail
Right
class Date:
def __init__(self, day, month, year):
if month > 12:
raise Exception("Month should not exceed 12")
#
# etc ...
self._day = day
self._month = month
self._year = year
startDate = Date(3, 11, 2020)
# OK
startDate = Date(31, 11, 2020)
# fails
startDate.setMonth(13)
# fails since invariant makes object immutable
Detection
- It's difficult to find missing preconditions, as long with assertions and invariants.
Level
[x] Beginner
Why the Bijection Is Important ️
In the MAPPER, a person cannot have a negative age or an empty name.
If your code allows these states, you break the bijection.
When you maintain a strict one-to-one relationship between your business rules and your code, you eliminate a whole category of "impossible" defects.
AI Generation
AI generators often create "happy path" code.
They frequently skip validations to keep the examples short and concise.
You must explicitly ask them to include preconditions.
AI Detection
AI tools are great at spotting missing validations.
If you give them a class and ask "What invariants are missing here?", they usually find the missing edge cases quickly.
Try Them!
Remember: AI Assistants make lots of mistakes
Suggested Prompt: Add constructor preconditions to this class to ensure it never enters an invalid state based on real-world constraints. Fail fast if the input is wrong.
Conclusion
Always be explicit on object integrity.
Turn on production assertions.
Yes, even if it means taking a small performance hit.
Trust me, tracking down object corruption is way harder than preventing it upfront.
Embracing the fail-fast approach isn't just good practice - it's a lifesaver.
https://coderlegion.com/7024/fail-fast-principle
Relations ❤️
https://coderlegion.com/7246/code-smell-01-anemic-models
https://maximilianocontieri.com/code-smell-189-not-sanitized-input
https://maximilianocontieri.com/code-smell-40-dtos
https://en.wikipedia.org/wiki/Object-Oriented_Software_Construction
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
https://maximilianocontieri.com/software-engineering-great-quotes
This article is part of the CodeSmell Series.
https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code