Skip to content

Instantly share code, notes, and snippets.

@zewt
Created December 3, 2017 21:15
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 zewt/f8d8d90b70bd406ea71250d4db5713bd to your computer and use it in GitHub Desktop.
Save zewt/f8d8d90b70bd406ea71250d4db5713bd to your computer and use it in GitHub Desktop.
Flatten your conditionals
Don't nest conditionals when you can return. Don't do this:
int do_task()
{
if(get_task())
{
// Success. Do lots of stuff with the data.
// (insert 30 lines of code here)
return n;
} else {
// There's nothing to do.
return 0;
}
}
This puts the entirety of this fictional 40-line function inside an extra conditional block.
That makes the whole function more complicated, and when you get to the end you have to scroll
around to see what the else is for. Instead, do this:
int do_task()
{
if(!get_task())
{
// There's nothing to do.
return 0;
}
// Success. Do lots of stuff with the data.
// (insert lots of code here)
return n;
}
Now, the conditional is just a few lines, and then it goes away and doesn't complicate the whole function.
You dont' have to remember or think about it at all once you get past it, and you can jump into the function
in the middle without having to scan upwards to see why you're inside a block.
This gets more and more important when this happens multiple times in a function. This is horrifying, and you see it all the time:
int do_task()
{
if(get_task())
{
if(task_ready())
{
if(perform_task())
{
return n;
} else {
return 0; // from perform_task
}
} else {
return 0; // from task_ready
}
} else {
return 0; // from get_task
}
return 1;
}
Don't do that! This is really just a linear sequence of operations, and it's putting the returns
so far from the condition they're for that you have to comment them to remember what's what.
Just flip the conditions and write it linearly:
int get_data()
{
if(!get_task())
return 0;
if(!task_ready())
return 0;
if(!perform_task())
return 0;
return 1;
}
If your code is like this but you can't return because you need to do something at the end, you probably
want to break it apart into a separate function anyway.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment