Abstraction allows us not to think about the details of the implementation and to focus on its use. Moreover, the implementation of an abstraction can be rewritten, if necessary, without fear of breaking the code that uses it. But there is another reason why you need to use abstraction-maintaining invariants.
In programming, an invariant is a logical expression that defines the consistency of a state or data set.
Let's look at an example. When we described the constructor and selectors for rational numbers, we implicitly implied the following invariants:
num = make_rational(numer, denom)
numer == get_numer(num)
# True
denom == get_denom(num)
# True
By passing the numerator and denominator of the rational number constructor, we expect to get the same numbers when we apply the selectors to the rational ones. It is how we ensure that the abstraction works — we test the code in practice.
Invariants exist for every operation. And they can be tricky. For example, we can compare rational numbers to each other, but not directly, because we can represent the same fractions in different ways: 1/2
and 2/4
.
Code that doesn't take this into account won't work:
num1 = make_rational(2, 4)
num2 = make_rational(8, 16)
num1 == num2