Error Handling: Silent Bullets

Error Handling: Silent Bullets

Ahmed Ramy
Β·Jul 19, 2022Β·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • The Problem πŸ’₯
  • Silent Bullet πŸ”«
  • Remedy 🌿
  • Conclusion

Hello there! πŸ‘‹

It’s been a while, and I really missed writing a blog early in the morning! Now that I have some sort of free time, I wanted to discuss some techniques in Error handling over the coming days that I learned, and well, thought it would be interesting to share! πŸ˜„

I wanted to start with something that may not be obvious all the time, especially when you prefer to be safe away from crashes, which is unwrapping optional variables

The Problem πŸ’₯

func handle(deeplink: String) {
  guard let deeplinkUrl = URL(string: deeplink) else { return }
  ...
}

In the current context of the above method, you need to make sure that the URL is unwrapped after receiving the deeplink, and if the deeplink is invalid for whatever reason, we won’t continue executing the method

Seems… kinda normal, right?

Nope, it’s not always okay to early return silently, while it may not affect the program’s execution or create any bug (not always)… It may be a sign of something went wrong, without firing any alarms, like a bug hiding in plain sight, like a...

Silent Bullet πŸ”«

Silent Bullets are parts of your code that fail without firing any warnings, and the pattern where you unwrap a variable without handling the case where its indeed nil may create weird behaviors, and we, the developers, should be notified when something like this goes wrong

Remedy 🌿

Logging such behavior should be what you do in such case, to give you a second pair of eyes when something goes wrong, be it a technical issue, bad usage from another team, or a glitch in the matrix

Cat walking in Matrix

For the scope of this post, we will stop at just printing this issue, in the next post we will talk more about Logs and why you need them, then walk you through a better approach than just printing it

func handle(deeplink: String) {
  guard let deeplinkUrl = URL(string: deeplink) else { 
    debugPrint("coudln't unwrap \(deeplink) as a URL for handling it.")
    return
  }
  ...
}

Conclusion

Not always unwrapping optional parameters may be a good thing, when reviewing/writing unwrapping code, ask yourself, is it normal for my use case that this variable may become nil by design? Or if it became nil that indicates a problem? πŸ€”

Happy Coding!

Β 
Share this