How to Design Early Returns in C++ (Based on Procedural Programming) – Fluent C++
Posted by jpluimers on 2019/05/15
One more thing to take away from Procedural Programming: It’s Back? It Never Went Away – Kevlin Henney [ACCU 2018] – YouTube was explained in [WayBack] How to Design Early Returns in C++ (Based on Procedural Programming) – Fluent C++.
Though in C++, it applies to all programming languages that stem from a procedural background (Pascal, C#, Java, golang, to name just a few).
The article is about keeping an if/else-if/else tree, even when they can be removed becomes some of their bodies perform an early return, as
In C++, as well as in other languages, the
return
keyword has two responsibilities:
- interrupting control flow,
- yielding a value.
It basically comes down to this argument:
Essentially, the argument for Code #1 is that you need to know less to understand the structure of the code.
Indeed, if we fold away the contents of the if statements, Code #1 becomes this:
1234567 bool isLeapYear(int year){if (year % 400) { ... }else if (year % 100) { ... }else if (year % 4) { ... }else { ... }}The structure of the code is very clear. There are 4 different paths based on the
year
, they’re independent from each other, and each path will determine the boolean result of the function (if it doesn’t throw an exception).Now let’s see how Code #2 looks like when we fold away the if statements:
12345678 bool isLeapYear(int year){if (year % 400) { ... }if (year % 100) { ... }if (year % 4) { ... }return false;}And now we know much less. Do the if statements contain a
return
? Maybe.Do they depend on each other? Potentially.
Do some of them rely on the last
return false
of the function? Can’t tell.With Code #2, you need to look inside of the if statement to understand the structure of the function. For that reason, Code #1 requires a reader to know less to understand the structure. It gives away information more easily than Code #2.
–jeroen
via [WayBack] Kevlin Henney – Google+: How to Design Early Returns in C++ (Based on Procedural Programming) – Fluent C++
Leave a comment