Practical tips for functional error handling
A week into refactoring, Steve was making progress, but he felt overwhelmed by all the new concepts.
Steve: I’m not sure I’m doing this right…
Julia: Don’t worry, it’s normal to feel that way when learning a new paradigm. Let me share some practical tips that’ll help you navigate this new territory.
Avoid null with options
Try to never return null. It sounds simple, yet it’s a pitfall waiting to trip up the unwary. Why? Because nulls are very easy to get, however, it is much harder to handle them properly and if you don’t do it well, it can lead to cascading failures:
public User FindUser(string login) { // This can return null! return users.FirstOrDefault(u => u.Login.Equals(login)); }
Turn this around:
public Option<User> FindUser(string login) { var user = users.FirstOrDefault(u ...