Code Review: Issue 2

Tip #8: Goto statements are NEVER necessary!

This is C/C++ specific. I wish programmers would forget that goto statements existed. The only time you should ever worry about a goto is if you find it in someone else’s code and you have to fix it. Because a goto is a problem. They create control flow panic. There is nothing you can do with a goto that you can’t also do with more readable, comprehensive code structures, so use those.

 

Tip #9: Meaningful variable names help you and your collaborators

It may be tempting to write code with variable names like c, s, x, y, i… but don’t do it. This creates confusion. For example:

void iter_string(string s)
{
    int x = 0, y = 0;
    char c, b = 'y', a = 'n';

    for(int i = 0; i < s.len(); ++i)
    {
        c = s[i];

        if(c == b)
        {
            x = 1;
        }
        else if(c == a)
        {
            y = 1;
        }
        else
        {
            x = 1;
            y = 1;
        }
    }
}

It might make your code “shorter,” but if you’re losing track of what your variables refer to while you’re writing your code, chances are nobody else is going to be able to figure out what they mean in the first place.

 

Tip #10: Always #define (or equivalent) your magic numbers

“Magic numbers” are numbers that are used in an expression without having an obvious purpose. For example,

void purchase(int num)
{
    return (cents / 100) - (5 * num);
}

What is the multiplier 100 for? Maybe it seems implicitly obvious because of the variable naming, but what about the – 5? Wouldn’t it be easier if it were written this way:

void purchase(int num)
{
    return (cents / CENTS_IN_DOLLAR) - (PRICE_OF_OBJECT * num);
}

I certainly think so. So whenever possible, give your values names.

 

Tip #11: Use scope brackets for all of your ifs and whiles

One-liners like this don’t require you to use scope brackets in C/C++:

if(somecondition)
    dosomething();

but when you go to add another action to this if, you’re likely to do this on accident:

if(somecondition)
    dosomething();
    dosomethingelse();

which won’t actually do what you want (dosomething() will be executed if somecondition is true, but dosomethingelse() will be executed regardless). If you get in the habit of adding the scoping brackets, you can avoid odd errors like this.