A piece of code that bugs me a lot from time to time:
var aThingThat99PercentNotNull = someService.GetThingThat99PercentNotNull(thingId);
if (aThingThat99PercentNotNull != null) {
// Nested ifs and more nested ifs
// Or some twisted business logic
....
}
Some of you reading this might not see anything wrong, and I don’t blame you. We each has preferences, yes, and some people actually enjoy reading nested ifs like some kind of indent hadouken. If you are one of such people, I guess we can be friends in real life, but I would roast you if we were coding friends 24/7.
Really, have a good look at how ridiculous that code is. Why on earth you want to check if something is not null if you are like 99% sure that it will never be null?? Have you ever considered the whole point of writing code that handles edge cases?? This is, apparently, some kind of half-baked attempt at ensuring we handle edge cases, or likely to meet the code KPI.
But you still can write long pieces of code and not get to the nested if hell. Hear me out:
var aThingThat99PercentNotNull = someService.GetThingThat99PercentNotNull(thingId);
if (aThingThat99PercentNotNull == null) {
// Handle the edge case here, simple as that?
// Or just simply return the error, we can deal with this later
return emptyList;
}
// Do whatever you want next
var anotherThing = anotherService.GetThingFromThing(aThingThat99PercentNotNull);
See? It is not that hard. And much more readable. Save some of your cognitive load by not looking at indents after indents. If your coworkers or friends do this, please tell them. Time is precious and so our cognitive load.
I was so lucky I’ve got to learn not to do this by following one of the best practices of Go:
thing, err := getThing(id)
if err != nil {
return nil, err
}
return thing, nil
Errors as values are godsend to me. And I don’t like try/catch mechanism either since there might be 100 lines of instructions inside a try block, do you really want to debug that? Writing error handling for each return is quite time-consuming, I got it, but I say the time we can spend writing template-ty things save hours of debugging.