Search code examples
c++invariants

Is there a common way to implement invariants?


This is a basic example where i want to add intvariants, for example that my age can't be under 0.

#include "InvariantTest.h"
#include <iostream>
#include <string>
using namespace std;


int age;
string name;


void setAge(int a) {
    age = a;
}

void setName(string n) {
    name = n;
}

string getNameandAge() {
    string both;

    both = name + to_string(age);
    return both;

}

I can't find a norm how to implement invariants in c++.


Solution

  • Usually you’d want to at least add a debug assertion assert(a > 0) (this will throw an exception when running the debug build of your program) in addition to the if (a > 0) age = a;

    You can also probably throw a full-fledged exception instead of asserting when the contract is not upheld, so that the program will terminate early. You can also catch the exception at the method callsite and handle the error gracefully.

    Other error handling techniques exist, and some people prefer them over exceptions, but that is out of scope of the question.