What is class Invariant
An invariant in Object-Oriented programming refers to some set of conditions or assertions that need to hold throughout the life of an object of a class. These assertions need to hold from the time the constructor is called for an object, at the end of each member (mutator) method call to the end of the destructor call. These conditions verify that an object’s behavior is justified during its lifetime and that the object maintains its well-defined state as intended. The invariant, however, need not hold true during the execution of a mutator method but must hold true at the end of it.
Creating a snake game –
Let’s say we were creating a snake game and our snake had the ability to teleport itself a few blocks in some direction. Let us also define our invariant that our snake’s head should not cross the playground bounds. Now, if we ensure that our invariant holds at the end of the function where we implement our teleportation ability, we are good. Otherwise, our assertions will fail, and we will find out that there probably is a bug in our code.
Code Implementation in C++ :
As a good programming practice, an invariant private member method is created whose duty is to check that all necessary conditions stay uncompromising and that all methods can make reasonable assumptions about the state of the object. We call this invariant member method at the end of constructors and every mutator method.