We all love apps that “just work”. There are several keys to achieving a seamless experience for users, and one of them is chosing the right framework for handling nasty scenarios.
A common programming practice is to write your program’s control flow as if it were to follow the “golden path”. In other words, the commonly (and preferably) executed portion should always be above the edge cases. For example:
func divide(number: Int, divisor: Int) -> Int? {
if divisor != 0 {
return number / divisor
}
else {
return nil
}
}
As the rules of mathematics don’t allow us (or the user) to divide a number by zero, we must check if divisor
will be zero before proceeding with the division. In this case, divisor
not being zero is our “golden path”, so rather than being pessimistic straight off the bat and checking if divisor == 0
, we are optimistic.
This is just a small part of our framework for handling nasty scenarios. You’ll notice our function above is aware of the possibility of our division going awry, but doesn’t seem to handle it very gracefully. It represents all nasty outcomes by returning nil
. So nil
could mean “something went wrong because you divided by zero”, or “something went wrong because there was an integer overflow”.
This week, Said Sikira writes about the Result
construct, which you can use as part of your framework for dealing with nasty scenarios (a.k.a. “error handling”). It’s useful for programmers accross the board, and will help you provide your users with useful and actionable errors (if at all!).
Follow the golden path.
Shout out to Abizer Nazir for first introducing me to the notion of the golden path.
Ariel is the former editor of SitePoint's Mobile Channel. He worked on more than 10 different apps currently available on the App Store, and plans to release many more. He loves writing, mobile devices, hackathons, and blockchains.