Invariants
Understand invariants and how they function to make the properties stronger and more reliable.
We'll cover the following
What are invariants?
Some programs and functions are complex to describe and reason about. They might need many small parts to work correctly to be functional, or we may not be able to assert their quality because it’s difficult to define. For example, a judgment about whether a meal is good is subjective, although it could include criteria. The criteria could include whether the ingredients were cooked adequately, whether the food is served at the correct temperature, whether the meal is too salty, sweet, or bitter, etc. These factors play a part in the decision of “whether the food is good or not.”
Similarly, in a software system, we can identify similar conditions that should always remain true. These are called invariants.
Advantages of invariants
Testing with invariants is a great way to get around the fact that things may just be ambiguous otherwise. If an invariant were to be false at any time, we would know something isn’t functioning properly. Here are some examples:
- A store cannot sell more items than it has in stock.
- In a binary search tree, the left child is smaller and the right child is greater than their parent’s value.
- Once you insert a record into a database, you should be able to read it back and not see it as missing.
A single invariant on its own is usually not enough to show whether a piece of code is working as expected. But if we can come up with many invariants and small things to validate, and if they all always remain true, we can gain a lot more confidence in the ability of our codebase to work well. Strong ropes are built from smaller threads pulled together. In papers or proofs about why a given data structure works, we’ll find that almost all aspects of its success come from ensuring a few invariants are respected.
For property-based testing, we can write a lot of simple properties, each representing one invariant. As we add more and more of them, we can build a strong test suite that overall demonstrates that our code is rock solid.
Get hands-on with 1400+ tech skills courses.