DEV Community

Discussion on: Null Object Pattern

Collapse
 
craigbrad profile image
Craig Bradley

It would have been nice to see what some of the pro's and con's are of using this pattern.

I've seen a few comments stating that it's bad because there is more code. More code does not mean that the code is cleaner. We could write nested if statements on one line using ternary, but I'm sure you understand why this is a bad idea.

We shouldn't be checking if an object is nil or null as this means we're concerned with types. Ruby in particular is somewhere you would probably see this pattern as it encourages duck typing and polymorphism. The null object pattern is really useful when you're passing objects around the stack and calling methods in multiple places. Everywhere you call a method on an object you would also firstly need to check if the object is nil. Yes, we should never really have null objects, but we always will, as exceptional behaviour will always be present. Systems fail, software fails.