设置一个类的属性等于同一类的方法的输出有什么意义?

huangapple go评论69阅读模式
英文:

What is the point of setting an attribute of class equal to output of a method of the same class?

问题

这个问题应该适用于所有面向对象编程语言,尽管我只熟悉C++和Python。我在几个代码库中看到过这种情况,而且在Python和C++中也见过。我将在Python中进行示例:

class sim:
  def __init__(self, name="sim_today"):
    self.name = name
    self.properties = self.compute_properties()
  def compute_properties(self):
    # <insert logic to compute properties>
    return properties 

我不理解这种设计方式。为什么不直接在compute_properties中设置properties,像这样:

class sim:
  def __init__(self, name="sim_today"):
    self.name = name
    self.compute_properties()
  def compute_properties(self):
    self.properties = <insert logic to compute properties>
英文:

This question should pertain to all OOP languages, though I'm only familiar with C++ and Python. I've seen this in several codebases and have seen this in Python and I think also in C++. I will illustrate in Python:

class sim:
  def __init__(self, name=&quot;sim_today&quot;):
    self.name = name
    self.properties = self.compute_properties()
  def compute_properties(self):
    # &lt;insert logic to compute properties&gt;
    return properties 

I don't understand this type of design. Why not just set properties directly within compute_properties like:

class sim:
  def __init__(self, name=&quot;sim_today&quot;):
    self.name = name
    self.compute_properties()
  def compute_properties(self):
    self.properties = &lt;insert logic to compute properties&gt;

答案1

得分: 1

分离关注点建议一个方法通常应返回一个值或改变对象,但不要同时做两者。构造函数是初始化对象属性的明显地方,这种设计使清楚了分配的值是有条件的,而不是像选择属性或不分配任何东西这样更一般的情况。

当然,当值可以从其他属性计算时,这使得被分配的值成为缓存;请记住,缓存失效是计算机科学中的两个难题之一(另一个是命名和一差一错错误),因此只有在计算值昂贵时才有正当理由。

英文:

Separation of concerns suggests that a method should generally return a value or mutate the object but not both. The constructor is the obvious place to initialize the object’s attributes, and this design makes it clear that what is conditional is what value is assigned and not anything more general like selecting an attribute or not assigning anything.

Of course, when the value can be computed from other attributes, that makes the one assigned a cache; recall that cache invalidation is one of the two hard things in computer science (along with naming things and off-by-one errors), so this would be justified only if the value were expensive to compute.

huangapple
  • 本文由 发表于 2023年2月18日 09:04:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定