Last active
February 18, 2023 15:26
-
-
Save nboutin/9418bc7452145fa577de5a0a551273a3 to your computer and use it in GitHub Desktop.
Solve if-else indentation hell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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