Simplifying Conditional Logic

Simplifying Conditional Logic

3 tips to improve the conditional logic of your code.

In this article I will go over three ways you can better write your code's conditional logic, making it more readable, easier to understand, and work with.

Prefixes

In order to explicitly convey that a variable is a boolean variable, you can prefix it with either is, has, or should, whatever suits best with the business domain's language, they make the names of the boolean variables much clearer.

Example:

Samples of boolean variables with prefixes

Variables

Another thing you can do is to extract boolean logic to variables and giving the variables meaningful names. This makes the code much easier to read and understand.

Samples of extraction of boolean logic to variables

Now, take into account, this technique should be used with pragmatism as any other technique, sometimes it makes more sense and is more readable by inlining the boolean logic.

Take this as a tip, because from what I've seen, this technique can be used in many places and would've made the code more readable and easier to understand.

Functions

Instead of extracting the logic to variables, in some instances, it can make sense to extract them to functions, if you for example have to do a lot of logic or already want to cover edge cases.

Example with functions returning the boolean logic

Conclusion

There are ways we can improve the conditional logic of our code, making it more readable and easier to understand.

The last two techniques when it comes to extracting, should be used with pragmatism, not in every scenario do they fit, in some cases, it is actually more readable to inline the logic.