Why you shouldn’t use the Else statement in your code
Bending the Clean Architecture Principles
Introduction
In most of today’s languages, you have a famous If and Else statements that lets you decide the fate of your function based on a condition. While this is considered a standard, I have been writing for 1 year now without using the Else keyword and here’s what I learned and my take on this.
Why is it worth a post
You will definitely find this odd. But I never intentionally stopped using the Else in the first place. It happens to be a natural transition that I think every developer will make regardless of the language. Note that I am mainly talking about Object Oriented Programming…
I saw once people talking about this and I thought: Wow ! I am already doing this ;)
Why
I am not a huge fan of all the rules and principles involving clean code such as SOLID. I think we shouldn’t follow them blindly so I will explain with each reference.
When you have a function with an IF-Else statement. Practically, your code does two things (minimum). Based on a certain condition, you execute a certain code block.
So we can say that your function handles two scenarios at least. While this does not necessarily break the SRP (Single Responsibility Principle), it definitely indicates that you CAN do more splitting in this function.
If this didn’t convince you enough to extract some code into local functions, there’s another common principle involving code readability in the community. This is the single level of indentation in each function.
I know that this isn’t applicable in all scenarios, but from my personal experience, the cases where this is not a thing are very rare…
So hopefully now, each function handles a single and atomic responsibility. But that didn’t quite solve our problem right?
In fact it did, there’s only one more step to go. I might get slammed for saying this, but I am against the famous Single Exit Point approach. You don’t need to add a bunch of code that will never be executed just to exit last.
Naturally, most of the elses at this point will be removed and replaced with a return statement to exit directly.
The Result
With all this steps, you end up with minimal functions executing only the required instructions. Your entire code does not contain 10 level of absurd branching or indentation.
Conclusion
Just like the switch statement, I think the usage of the Else keyword is pretty rare. I managed to stopped using it for a year now without even noticing. I have literally text searched in my source code to make sure ;)
Disclaimer
This does not include frameworks that behave in a specific way such as Blazor, Controllers etc… I am mainly talking about your domain and business logic.