-3

I have a class constructor that needs to perform a couple checks. It is checking a file for the occurrence of a few tags. I use a function that checks for the tags and returns a boolean value depending on whether the tag was found. If the tag was not found it calls return, stops executing the constructor and sets the alive flag to false. I cannot throw an exception in this case.

At the moment the code looks like this:

if (!tagExists(tag1))
    print(tag1 + " failed")
    alive = false
    return
if (!tagExists(tag2))
    print(tag1 + " failed")
    alive = false
    return

And this continues for the amount of tags there is. What would be the best way to refactor this? As I said, I cannot use exceptions.

closed as off-topic by gnat, user22815, enderland, Bart van Ingen Schenau, amon Feb 13 '17 at 15:24

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in explaining, writing or debugging code are off-topic here. These can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question (see Minimal, Complete, and Verifiable Example)." – Community, enderland, amon
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    Seems like you're doing a lot of the same things over and over. Try a function. Might prevent silly mistakes like saying tag1 failed when tag2 failed. – candied_orange Feb 13 '17 at 4:41
1

It seems the natural way would be to write a loop. You could have an array of the tags and do something like this:

const Tag_t tags[NUM_TAGS] = { tag1, tag2, tag3 ... };
for (int i = 0; i < NUM_TAGS; ++i)
{
    if (!tagExists(tags [ i ]))
    {
        print(tags [ i ] + " failed");
        alive = false;
        return;
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.