user3087000
user3087000

Reputation: 751

What is null object pattern?

I think null object pattern is a way to reduce duplicated code for checking nil or doing something depending on the nil value. Is my thought wrong?

I refactored this code with null object: https://github.com/WithGJR/null. Please tell if I have something wrong.

Upvotes: 0

Views: 716

Answers (1)

user1375096
user1375096

Reputation:

From your example, the so called Null Object concept is to not use Ruby nil in your code, because nil doesn't respond to the methods of Subscription class.

In the case of nil, you have to implement

def price
   # this will generate a NoMethodError: undefined method `price' for nil:NilClass
   subscription.price
end

as something like this:

def price
   subscription.try(:price) || 0
   # or if you don't use rails try method
   # subscription.nil? ? 0 : subscription.price
end

The introduction of NullSubscription makes sure that your @subscription object in user.rb always responds to methods charge, has_mentoring?, price, and those methods always return a proper value (no matter whether it's a real Subscriptoin instance or NullSubscription instance). So you can directly call subscription.price regardless.

(thanks for @FrederickCheung) If you search Rails source code for module Null and class Null, you could find some examples for this pattern.

In Rails app, people tend to use Rails try and try! methods to deal with nil object.

Upvotes: 3

Related Questions