Last Updated: February 25, 2016
·
326
· themichael'tips

Cpp: DRY for error check using preprocessor

Introduction

In order to deal with many checks conditions, the below code snippet is rapid to implement and is DRY.

Use case

Suppose to parse a json string: how many different cases to control ?!
<br>Let's suppose a method like the below:

void JsonParser::parsing_json(const json&obj) {
    auto it = obj.cbegin();
    int position = 0;

    while(it != obj.cend()) {
        if (it->value() != "{")
            throw my_exception("Error at position {}", position);

        //...code...and other check
        if (!it->find("}")) 
            throw my_exception("Error at position {}", position);

        //...code...and other check
        if (!it->find("[")) 
            throw my_exception("Error at position {}", position);

        //...code...
    }   
}

Using inner preprocessor the code will turn to:

void JsonParser::parsing_json(const json&obj) {
#define JSON_CHECK(x) if (x) throw position;

    auto it = obj.cbegin();
    int position = 0;

    try {
        while(it != obj.cend()) {
            JSON_CHECK(it->value() != "{"])

            //...code...and other check
            JSON_CHECK(!it->find("}"))  

            //...code...and other check
            JSON_CHECK(!it->find("["))  

            //...code... 
        }   
    } 
    catch (int pos) {
        //...customize your exception here
        throw my_exception("Error at position {}", pos);
    }

#undef JSON_CHECK   
}

Note

Preprocessor are not always the best solution, but each case is different and you should consider your specific case before accept the statement "preprocessor must be avoided" ^__^
<br>Enjoy