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

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

问题描述

我正在阅读清洁代码"一书,并且正在为一个概念而苦苦挣扎.在讨论对象和数据结构时,它声明如下:

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

  • 对象将其数据隐藏在抽象之后,并公开对这些数据进行操作的函数.
  • 数据结构公开了它们的数据并且没有任何有意义的功能.

所以,我从中得到的是我的对象上不应该有任何公共属性,我应该只有对属性执行操作的方法.如果我确实需要访问属性,它们应该在一个数据结构上,它可以从我对象的方法返回?使用这种方法,我的对象上的 Height 属性似乎需要一个 GetHeight() 和 SetHeight() 方法,而不仅仅是使用 getset财产.

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; }

进入

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天全站免登陆