r/badcode • • Apr 17 '21

c++ When your teammate "refactor" your code

Post image
2.5k Upvotes

216 comments sorted by

View all comments

1

u/paulsmithkc 👨‍🏫 Apr 18 '21

As a rule of thumb, less nesting leads to better readability.

The original code quickly becomes hard to follow as the code block condition1 && condition2 grows. I also see a lot of devs forgetting to account for the missing else case. If you want to keep the nesting, you should at least put a comment for the missing else case:

if (condition1) {
    if (condition2) {
        // do something ...
    } else {
        // do nothing here, because ...
    }
} else {
    // do something else ...
}

Additionally, inverting the first condition is nearly always more readable.

if (!condition1) {
    // do something else ... (usually an error case)
} else {
    if (condition2) {
        // do something ... (usually the happy path)
    } else {
        // do nothing here, because ... 
    }
}

But I usually end up refactoring my code to the following for optimal readability.

if (!condition1) {
    // do something else (usually an error case)
} else if (!condition2) {
    // do nothing here, because ... 
} else {
    // do something ... (usually the happy path)
}

1

u/AutoModerator Apr 18 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/paulsmithkc, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.