r/badcode • • Apr 17 '21

c++ When your teammate "refactor" your code

Post image
2.5k Upvotes

216 comments sorted by

View all comments

76

u/apieceoffruit Apr 17 '21

its funny for all the versions in the comments, I am surprised to see nobody has a version with a guard clause and no cyclomatic complexity:

void foo()
{
    if(!condition1)
    {
        do_anything2();
        return;
    }

    if(condition2) 
        do_anything1();
}    

Obviously the silly order dependent names make it more confusing. but a standard for this kind of thing is:

void foo()
{
     if(cantDoThing)
    { 
         ShowWarning();
         return;
    }   

    if(someCondition)
          DoThing();
}

one of the below comments says to always add an else statement, I 100% disagree.

else statements are flow statements that increase the cognitive complexity of a statement and tie two conceptually unrelated concepts.

Instead, evaluate your "guard" statements, exit early if you can, so as you get down further the code gets simpler, not more complex.

instead of nesting in a tree of conditionals, knock down and remove ones you can evaluate early.

In fact Jeff Bay in his thoughtworks anthology book suggests his own rules for "object calisthenics" that includes never using the else keyword.

Not sure I subscribe to that one myself, but I do admit I don't use it very often. rarely does it make code easier to read.

-6

u/c3534l Apr 18 '21

While its fine for something really short (and we don't know OPs code actually was short since it was clearly a fictionalized version of what he actually wrote), the early return statement is distasteful. You should have very clear entry and exit points. The control flow was clear in OPs original and starts to get muddy here. Getting rid of else statements sounds like just about the worst idea I could think of. I much prefer Haskell's approach of requiring an else statement. Can't say I approve of your approach for anything other than the most trivial of implementations.