Handling Colossal Conditions in Go
Conditions are common in programming languages. When conditions are small, they are easy to understand. When conditions are colossal, they could be scary. Some common issues we see are –
Complex conditions can be hard to read and maintain. Things that look obvious while writing those monster conditions could make you feel alienated within a week.
We see conditions within the same function repeat multiple times. A change in the condition will require us to change in the instances where it repeats.
It’s hard to stare at a condition with five “and”s and six “or”s to know what’s happening. I have personally felt it scary to touch those evil lines.
At VIS, while creating a Google Calendar like event scheduler, I came across all three situations. I could imagine how things could go haywire and less readable when the complexity of some of the conditions was increased.
Let’s take a simple example
Here, the function schedule returns a list of events. Events can be daily or monthly, should either return the “qty” number of events or until “endDate”.
The condition to check when the event generation should be stopped is repetitive, a little complex and hard to comprehend. In the long run, this function could get more complex, there could be more clauses added to the condition.
Closures for the rescue
Let’s see how we can make this better with closure. Check my blog — Go Closure to know more about Closures
We refactored the condition into a closure and assigned it to a variable proceedToNextEvent.
The variable name for the closure makes it clear what the condition is trying to do. With closures, the condition, rather, conditions are more readable as it doesn’t have to be stuck in a single line. In the long run, it can be made more complex without making it convoluted to understand. It’s not repetitive.
You may argue that we can create a separate function rather than a closure. Yes, you can. I would prefer creating a separate function only when this condition is used in multiple different functions or methods.