Why I Stopped Using Else in Code
One change that can make a big difference in the readability and maintainability of C# code is avoiding the else
keyword. This might seem unusual for junior developers, but by removing else
, the code becomes easier to read and maintain.

Now the question is: why avoid else
?
Using else
often leads to unnecessary nesting, which can complicate program flow. Instead, solutions like early returns or separating logic into individual methods can bring simplicity and make the code easier to manage.
We’ll use C#
code and examples to describe different approaches.
Early Return
One of the simplest ways to avoid else
is by using an early return—when a certain condition is met, the function exits immediately. Here’s how it looks in practice:

So, by using early return we removed the else
blocks. The code is now simpler because we immediately return a value for each condition. In the end, only one general message remains for cases that are not covered. This structure makes it easier to read and maintain.
Replacing if-else with a switch statement
When we have multiple possible options, an if-else
chain can become tedious. Switch
expressions offer an easier and more readable way to handle multiple branches:

By using the switch
statement, our code becomes more transparent. Each option is clearly separated, which helps to organize the code better. With switch
, adding new cars becomes simpler without additional nesting.
Using the Car Description Lookup Dictionary
In situations where we have a large number of cars and need a flexible description system, we can use the Description Lookup approach. This approach combines an enum
for car brands and a Dictionary
to associate brands with descriptions.

This approach allows for easy addition of new car brands without needing to modify the main logic. If we want to add a new brand, we simply add it to the _carDescriptions
dictionary. This approach respects the Open-Closed Principle from SOLID, as the system is open for extension but closed for modification.
Benefits of Avoiding Else
- By eliminating
else
blocks, we reduce nesting, making the code easier to read. - Using early return,
switch
expressions, andDictionary
structures enables clearer branching of data flow. - The Car Description Lookup approach respects the Open-Closed Principle, as the code is open for extension but closed for modification.
For the End
Although else
is not necessarily bad, there are situations where avoiding it can improve code readability and maintainability. The techniques we covered: early return, switch
expressions, and Description Lookup help us create more flexible and sustainable code.
Next time you’re coding, try removing else
and simplifying the structure of your methods. These small changes can make a big difference in the quality and clarity of your code.
Cheers and Good Luck! 👋