【问题标题】:Naming Convention for Null Objects in Rails?Rails中空对象的命名约定?
【发布时间】:2015-10-11 08:13:31
【问题描述】:

对于 Rails 应用程序:是否存在命名映射到模型对象的空对象的命名约定?

例子:

#app/models/blog.rb
class Blog < ActiveRecord::Base
end

#app/models/null_blog.rb
class NullBlog # Null Objects are POROs, correct?
  def title
    "No title"
  end
end

# so to implement it I can do this:
blogs = ids.map{|id| Blog.find_by(id: id) || NullBlog.new}
# which allows me to do this and it works, even if some of those ids did not find a blog
blogs.each{|blog| blog.title}

NullBlog 是常规的吗?

this article by Avdi Grimm 和 Sandi Metz 的 Nothing is Something 演示都没有提到任何空对象命名约定。

【问题讨论】:

  • 顺便说一句,此块 { |id| Blog.find(id) || NullBlog.new } 将不起作用,因为如果未找到记录,带有 idfind 会引发异常。您可能想改用{ |id| Blog.find_by(id: id) || NullBlog.new }
  • @spickermann 不错!我会更新代码。

标签: ruby-on-rails ruby null-object-pattern


【解决方案1】:

目前还没有主流惯例。可能是因为Null Object Pattern 本身还没有被广泛使用。我遇到的对命名准则的唯一引用来自ThoughBot Style Guide,它使用它作为命名规则的示例:

更喜欢以领域概念命名类,而不是它们实现的模式(例如 Guest vs NullUser,CachedRequest vs RequestDecorator)。

在您的情况下,这将是为“空博客”找到“域语言”的问题。我发现找到这些术语的最佳方法是简单地与域用户讨论该主题,并记下他们使用的任何名词。这种方法在书Object Thinking中进行了概述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-01
    • 2012-03-17
    • 1970-01-01
    • 2023-03-03
    • 2017-03-10
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    相关资源
    最近更新 更多