Created
September 12, 2016 14:45
-
-
Save Qqwy/d0a276e1ac95bbcf329460d66e6f639d to your computer and use it in GitHub Desktop.
Shows why early exit on failure is a good code style strategy.
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
/* | |
In this snippet, the failure cases are not close to the conditions they belong to. | |
This makes it hard to track when which error case is triggered (especially when they are more than a screen height apart). | |
It also adds a lot of `{}` and indentation. | |
*/ | |
int someFunction(int foo, int bar, int baz) | |
{ | |
if (foo == 1) | |
{ | |
if (bar == 2) | |
{ | |
if (baz == 3) | |
{ | |
std::cout << "Success!\n"; | |
return true; | |
} | |
else | |
{ | |
std::cout << "ERROR: edge case 3 not supported;\n"; | |
exit(3); | |
} | |
} | |
else | |
{ | |
std::cout << "ERROR: edge case 2 not supported;\n"; | |
exit(2); | |
} | |
} | |
else | |
{ | |
std::cout << "ERROR: edge case 1 not supported;\n"; | |
exit(1); | |
} | |
} | |
/* | |
The same function, but this time with early exit on failure. | |
The error cases are directly connected to their conditions. | |
Also, there is no extra indentation happening. | |
*/ | |
int someFunction(int foo, int bar, int baz) | |
{ | |
if (foo != 1) | |
{ | |
std::cout << "ERROR: edge case 1 not supported;\n"; | |
exit(1); | |
} | |
if (bar != 2) | |
{ | |
std::cout << "ERROR: edge case 2 not supported;\n"; | |
exit(2); | |
} | |
if (baz != 3) | |
{ | |
std::cout << "ERROR: edge case 3 not supported;\n"; | |
exit(3); | |
} | |
std::cout << "Success!\n"; | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment