实际上是私有成员还是公共成员(封装有多重要?) [英] Private vs. Public members in practice (how important is encapsulation?)

查看:79
本文介绍了实际上是私有成员还是公共成员(封装有多重要?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

面向对象编程的最大优点之一就是封装,我们(或者至少我曾经学过)的真相"之一就是,应该始终将成员设为私有并通过以下方式使成员可用访问器和更改器方法,从而确保了验证和验证更改的能力.

One of the biggest advantages of object-oriented programming is encapsulation, and one of the "truths" we've (or, at least, I've) been taught is that members should always be made private and made available via accessor and mutator methods, thus ensuring the ability to verify and validate the changes.

不过,我很好奇这在实践中到底有多重要.特别是,如果您有一个更复杂的成员(例如集合),那么将其公开而不是使用大量方法来获取集合的键,从集合中添加/删除项目,可能会非常诱人.等

I'm curious, though, how important this really is in practice. In particular, if you've got a more complicated member (such as a collection), it can be very tempting to just make it public rather than make a bunch of methods to get the collection's keys, add/remove items from the collection, etc.

您总体上遵守规则吗?您的答案会根据是为自己编写的代码还是为他人使用的代码而变化?对于这种混淆,我还有其他更微妙的原因吗?

Do you follow the rule in general? Does your answer change depending on whether it's code written for yourself vs. to be used by others? Are there more subtle reasons I'm missing for this obfuscation?

推荐答案

这要视情况而定.这是必须务实决定的问题之一.

It depends. This is one of those issues that must be decided pragmatically.

假设我有一个表示点的类.我可以使用X和Y坐标的getter和setter,也可以将它们公开,并允许对数据的自由读/写访问.在我看来,这是可以的,因为该类的行为就像是一种荣耀的结构-可能附加了一些有用函数的数据收集.

Suppose I had a class for representing a point. I could have getters and setters for the X and Y coordinates, or I could just make them both public and allow free read/write access to the data. In my opinion, this is OK because the class is acting like a glorified struct - a data collection with maybe some useful functions attached.

但是,在许多情况下,您不想提供对内部数据的完全访问权限,而是希望依靠类提供的方法来与对象进行交互.一个示例是HTTP请求和响应.在这种情况下,允许任何人通过电线发送任何东西都是一个坏主意-必须由类方法对其进行处理和格式化.在这种情况下,该类被认为是实际对象,而不是简单的数据存储.

However, there are plenty of circumstances where you do not want to provide full access to your internal data and rely on the methods provided by the class to interact with the object. An example would be an HTTP request and response. In this case it's a bad idea to allow anybody to send anything over the wire - it must be processed and formatted by the class methods. In this case, the class is conceived of as an actual object and not a simple data store.

这实际上取决于动词(方法)是否驱动结构或数据是否驱动

It really comes down to whether or not verbs (methods) drive the structure or if the data does.

这篇关于实际上是私有成员还是公共成员(封装有多重要?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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