4 ms·
Good point -- I agree that pattern matching and monads are a more general solution to the Null Object problem. As for Java -- http://www.cs.oberlin.edu/~jwalke
by neilk 15y ago
Good point -- I agree that pattern matching and monads are a more general solution to the Null Object problem.
As for Java -- http://www.cs.oberlin.edu/~jwalker/nullObjPattern/ http://www.cs.oberlin.edu/~jwalker/nullObjPattern/ has examples. But the case of the empty linked list is stretching it a bit. Somehow it seems to me you ought to be able to have a regular linked list where the "nothing" behaviour did not need a whole other class.
I usually explain Null Object like this:
Think of a website where you have users who might be logged in or not. A naive way to express this would be that, if the user is not logged in, your getUser() method returns null.
But then you have to keep testing for null, over and over again, before you can do anything with the user. And the user-is-null case is suspiciously similar to user-is-not-authorized-to-do-this-thing.
Solution: make a hierarchy where there's an abstract User class, concretized by NonLoggedInUser and LoggedInUser. The NonLoggedInUser returns false for all isAuthorizedTo().
Now you always have a User, it's just that sometimes that User does "nothing". So you just ask if user.isAuthorizedTo('doTheThing').
Fowler generalizes this into the SpecialCase pattern. http://martinfowler.com/eaaCatalog/specialCase.html http://martinfowler.com/eaaCatalog/specialCase.html