干净的代码:如果对象有公共属性? [英] Clean Code: Should Objects have public properties?

查看:136
本文介绍了干净的代码:如果对象有公共属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读这本书清洁守则​​和我一个概念挣扎。当讨论对象和数据结构,它规定了以下内容:

I'm reading the book "Clean Code" and am struggling with a concept. When discussing Objects and Data Structures, it states the following:


  • 目标隐藏抽象背后的数据,并揭露了这些数据操作的函数

  • 数据结构暴露自己的数据,也没有有意义的功能。

那么,是什么我由此得到的是,我不应该有我的对象的任何公共财产,我应该只上的属性进行操作的方法。如果我需要访问的属性,他们应该是在一个数据结构,这可以从我的对象上的方法来退换吗?通过这种方法,看来我需要一个GETHEIGHT等到(),并自动调用setHeight()为我的目标在我的Height属性的方法,而不是仅仅使用的 GET 的设置的属性。

So, what I'm getting from this is that I shouldn't have any public properties on my object, I should only have methods that perform operations on the properties. If I do need to access properties, they should be on a Data Structure, which could be returned from a method on my object? With this approach, it seems that I would need a GetHeight() and SetHeight() method for my Height property on my object, rather than just using get and set of the property.

也许我不理解被建议什么,但是这是我的理解目标隐藏自己的数据的。如果你能帮助我理解这一点,我会非常感激!

Maybe I'm not understanding exactly what is being suggested, but this is my understanding of "Objects hide their data." If you could help me understand this, I'd greatly appreciate it!

在此先感谢!

推荐答案

公共属性都是精品。不必明确写入 GETHEIGHT等到()自动调用setHeight()方法是什么性质的全部意义。 C#中的属性的的数据;最好将它作为一对getter / setter方法​​查看。 (属性实际上是编译成在生成的IL的方法。)

Public properties are fine. Not having to write explicit GetHeight() and SetHeight() methods is what properties are all about. A property in C# is not data; it is best viewed as a pair of getter/setter methods. (Properties are actually compiled down into methods in the generated IL.)

该数据隐藏是可能的,因为你可以改变的实施不改变接口。例如,你可以改变

The data hiding is possible because you can change the implementation without changing the interface. For example, you could change

public int Height { get; set; }



into

public int Height { get { return m_width; } set { m_width = value; } }

如果你决定,你的对象应始终不散。使用你的类不需要任何修改的代码。

if you decided that your object should always be square. The code using your class would not need any modifications.

所以,如果你的对象公开的公共属性,但它仍然隐藏抽象背后的数据并公开对这些数据进行操作的功能,因为这本书建议。

So if your object exposes public properties, it still "hides it data behind abstractions and exposes functions that operate on that data", as the book recommends.

这篇关于干净的代码:如果对象有公共属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆