Skip to content

Instantly share code, notes, and snippets.

@Qqwy
Created September 12, 2016 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Qqwy/d0a276e1ac95bbcf329460d66e6f639d to your computer and use it in GitHub Desktop.
Save Qqwy/d0a276e1ac95bbcf329460d66e6f639d to your computer and use it in GitHub Desktop.
Shows why early exit on failure is a good code style strategy.
/*
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