First, full credit for the term “Null Hot Potato” goes to Reid Evans. He was presenting his talk “C# Without Nulls or Exceptions” at our local Windsor-Essex .NET Developers group. I don’t want to give away the talk, because I hope it gets posted online so you can watch it yourself. But I do want to dive into this one specific thing that Reid described as of the Null Hot Potato.
Not My Problem
It’s really a case of passing the responsibility. If your method handles null with null checks, but returns null, your just “passing the buck”. You’re basically saying to the caller: “I handled it properly, if you don’t that’s your problem”. Not exactly that friendly.
Easiest way to describe this through some trivial code snippet.
Here we have a simple method that takes a
string and returns a
string with no white-space.
What happens if we pass in
null as the parameter? Well because we are good developers, we used the null conditional operator to do our null check. Ultimately, this will return
null to the caller.
This is null hot potato.
Just because one piece of code that we may or may not own does the null check, does not mean anywhere else will. Ultimately null checks will be permeated through our code.
Your code, like mine, likely has null checks littered everywhere.
Shouldn’t it be reasonable to assume that if the signature of a method states that it takes a string and returns a string, it should actually do that. Wouldn’t that just make sense? How about a method that throws an exception? As the caller of that method, should I have any expectation it might throw?
This post is really an extension about my Avoiding the NullReferenceException post. Using an option type from the Optional package, we get rid ourselves of the null hot potato. We can be good code citizens and stop the madness of passing null off to the next caller.
Now if we are calling this method, there’s no surprises. We are always going to get an
Say no to null
Rid yourself of nulls and exceptions. Take the guess work out and simplify life by knowing if a method says its going to return a specific type, that it actually does. Love hearing your comments, please leave them bellow or on Twitter.Follow @codeopinion