NullObjectパターン
以下の例の EMPTY = EmptyUser.new がNull Object。
class EmptyUser
def initialize
@first_name, @last_name , @age = 'ごんべえ', 'ななしの', 0
end
def full_name
'ななしのごんべえ'
end
end
class Equipment
EMPTY = EmptyUser.new
def initialize(first_name, last_name, age)
raise ArgumentError, '無効な名前' if name.empty?
@first_name, @last_name, @age = first_name, last_name, age
end
def full_name
@last_name + @first_name
end
end
Null Objectパターンはオブジェクトに対して存在チェックを行う箇所が出てきたときに使う
以下は、 Rails tips: Null Objectパターンでリファクタリング(翻訳) からの引用
Userクラスで最新のpostを取得する際、Postクラスのオブジェクトの存在チェックを行い処理を分岐させており、UserがPostのことを知りすぎている。
class User < ActiveRecord::Base
has_many :posts
def latest_post_title
post = posts.order('created_at DESC').first
if post.present?
post.title
else
"No posts yet"
end
end
end
そんなんときに導入するのが Null Object。
class NoPost
def title
"No posts yet"
end
end
最新のpostのtitleを返す際、Null Objectの導入によりnilかどうかの分岐が消滅し、読みやすくなっている
class User < ActiveRecord::Base
has_many :posts
def latest_post_title
lastest_post.title
end
private
def latest_post
find_latest_post || NoPost.new
end
def find_latest_post
posts.order('created_at DESC').first
end
end
【参考】