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.
Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
Not My ProblemIt’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.
ExampleEasiest way to describe this through some trivial code snippet. Here we have a simple method that takes a
stringand returns a
stringwith no white-space. What happens if we pass in
nullas the parameter? Well because we are good developers, we used the null conditional operator to do our null check. Ultimately, this will return
nullto 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.
ExpectationsShouldn’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?
Option/MaybeThis 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