"else" is a code smell
I wince every time I see an else in a pull request. This is my personal taste and pretty controversial even in the team I work in, but here is how I am trying to make sense (mainly for myself) of why I feel that way.
Good code, to me, can be read sequentially. That makes the code easy to follow and understand. An else prevents reading code in sequence though.
At the time I first encounter an if, there is no way of knowing there will be an else coming up 50 lines later. So whenever I reach the else branch, I have to remember whatever the if condition was and mentally "jump back" the entire block. (It does not really matter how big the first block is - it is the mental backpedaling that throws me off.)
Strangely, I do not feel that strictly about ternaries. I think that is because it is clear an "else" is coming (also, they are usually very short so I can see both branches at a single glance). Even a switch does not really bother me because it is clear beforehand that there will be many branches coming up.
Luckily, there is almost never a case where I cannot get rid of an else easily:
- Using an early return (a guard clause)
- Using a lookup pattern (sometimes just a simple switch)
- Splitting code into separate functions
If none of the quick fixes are an option, I usually assume that there is a greater issue with my design. Then I go for a bigger refactor that makes the else no longer necessary down the line. The result so far has pretty much always been an overall improvement.
Thinking of else as a code smell and re-thinking how I structure my code whenever I come across one has had a big impact on the quality and maintainability of my code.
Admittedly, there have been cases where I have left an else untouched. However, I usually considered this a band-aid fix to avoid a bigger refactoring. I also try to avoid annoying my coworkers in their pull requests too much (this is a personal preference after all). Still, I can probably count the times I have kept an else in the last 5 years on one hand.