Why You Need Null Objects
Why You Need Null Objects
You have 2 free stories left this month. Sign up and get an extra one for free.
So, I wrote this piece “Stop Checking for Nulls” and it took some heat
from a few developers doubting the NOP’s usefulness. I figured I’d take
some time and provide additional examples.
For those who didn’t read the previous article and still don’t know what a
Null Object is, here’s a simple explanation.
Let’s have a look at some examples when the Null Object is more
expressive than just using nulls that’d easily wreck your application.
We’d often see something like this in a repository. Without the null-
object, the problem with this one line of code is that it’s lying about what
it returns and what it does.
Reading this code tells me I can always, as in, always, count on receiving
an Author type. But that’s not true, because some junior developer might
allow it to return null.
What to do instead
If you don’t want to apply the null pattern, instead write code that
actually tells you want to expect from it. The method signature about
would need to be changed to the signature below.
You see the question mark after Author, and the name now includes
“Default”? Now we know we’d possibly end up with a null calling this
method.
It’s not always you’d want to throw exceptions. As you’re obviously very
aware of, exceptions should only ever be thrown if something
exceptional happened.
Even the languages we use are old. Python is from 1990. Java is from
1995. Yeah, that’s right. Python is even more old school than Java. But
we still use them.
62 claps
WRIT T EN BY
Nicklas Millard Follow
Great Habits Every Why Programmers Need How to squash git How Do You Determine
Developer Should Work a Training Journal commits your Salary As A Startup
on Amy M Haddad in Level Up Srebalaji T hirumalai in Level CEO?
Daan in Level Up Coding Coding Up Coding brett fox in Level Up Coding
Go Make or New Linux user tries Make the switch to 5 T hings T hat Are Hard
Patrick Gopher in Level Up Windows, in 2020 Typescript today To Grasp When You
Coding Dominik Tarnowski in Level Up Taylor Coon in Level Up Start Programming
Coding Coding Daan in Level Up Coding