Skip to content

Instantly share code, notes, and snippets.

@nboutin
Last active February 18, 2023 15:26
Show Gist options
  • Save nboutin/9418bc7452145fa577de5a0a551273a3 to your computer and use it in GitHub Desktop.
Save nboutin/9418bc7452145fa577de5a0a551273a3 to your computer and use it in GitHub Desktop.
Solve if-else indentation hell
// Multiple level of nesting
void func()
{
if (...) {
if (...) {
...
} else {
if (...) {
...
} else if (...) {
...
} else {
...
}
}
...
}
}
// Convert if-else to if-return
void func()
{
if (!test()) {
handle_failure();
return false;
}
// do lots of work
}
// Multiple return in function not allowed
// Convert if-else to success/failure boolean
void func()
{
bool success = section_1();
if (success) {
success = section_2();
}
if (success) {
success = section_3();
}
}
// Shorter
void func()
{
bool success = section_1();
success = success && section_2();
}
// Shorter
void func()
{
bool success = section_1();
success &= section_2();
}
// In for-loop, convert if-else to if-continue
for(...) {
const T& element = *iter;
if (!test(element))
continue;
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment