首先,大家好
我想知道红宝石中对象包含的最佳实践。让我们描述一下上下文:
结果是我最终得到了可能非常大的嵌套对象,然后重复自己。
还有其他解决方案/模式可以这样做,但方式更简洁吗?有没有很好的例子?
谢谢 !
这是一个基本示例,但可以想象该对象在具有很多属性的情况下会变得更大。
require 'awesome_print'
class A
attr_accessor :title
def initialize(title)
@title = title
end
end
class B
attr_accessor :a, :level
def initialize(a, level)
@a = a
@level = level
# Here, I need to access to a.title
end
end
class C
attr_accessor :b, :name
def initialize(b, name)
@b = b
@name = name
# Here, I need to access to b.level
end
end
a = A.new 'test'
b1 = B.new a, 1
b2 = B.new a, 2
b3 = B.new a, 3
c1 = C.new b1, 'one one'
c2 = C.new b1, 'one two'
c3 = C.new b1, 'one three'
ap c1
ap c2
ap c3
c4 = C.new b2, 'two one'
c5 = C.new b2, 'two two'
c6 = C.new b2, 'two three'
# ... etc
结果对我来说似乎很脏(将大对象包含在其他大对象中)
#<C:0x000001011e9680 @b=#<B:0x000001011e9720 @a=#<A:0x000001011e9748 @title="test">, @level=1>, @name="one one">
#<C:0x000001011e9630 @b=#<B:0x000001011e9720 @a=#<A:0x000001011e9748 @title="test">, @level=1>, @name="one two">
#<C:0x000001011e95b8 @b=#<B:0x000001011e9720 @a=#<A:0x000001011e9748 @title="test">, @level=1>, @name="one three">
关于面向对象的事情是,您封装数据,方法以及其他对象以创建抽象。更多的抽象可以使您更轻松地推理项目,但同时也增加了复杂性并使项目更加复杂。我特别发现很难在这两者之间取得平衡。只有多年的实践才能实现。
如果封装的三个级别看起来太多了,请尝试将依赖项看作是代码的味道。
所有对象都代表有意义的,有用的抽象吗?例如:
A#title
某物level
给C使用在这里,B似乎只是在使用A并包含一个level属性,以便C可以使用它。这种抽象意味着有用吗?
如果C收到A对象,alevel
和a ,我们可以简化问题name
吗?
class A
attr_reader :title # Do you really need outside code to change this?
def initialize(title)
@title = title
end
end
class C
attr_reader :level, :name
def initialize(a, level, name)
@a = a
@level = level
@name = name
# Here, you access a.title to do whatever you did in B
end
def title
@a.title
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句