公共还是私人?
我真的不明白为什么将成员变量和成员函数设为私有通常是一种好的做法。
是为了防止人们搞砸事情/更多的是为了组织工具吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我真的不明白为什么将成员变量和成员函数设为私有通常是一种好的做法。
是为了防止人们搞砸事情/更多的是为了组织工具吗?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(7)
基本上,是的,这是为了防止人们搞砸事情。
封装(信息隐藏)是您正在寻找的术语。
通过仅向外界发布最少的信息,您可以根据需要自由地更改内部结构。
例如,假设您将电话簿实现为条目数组,并且不隐藏这一事实。
然后有人出现并编写代码来搜索或操作您的数组,无需通过您的“正常”界面。这意味着,当您想要开始使用链表或其他更有效的数据结构时,它们的代码将会中断,因为它使用了该信息。
这是您发布该信息的错误,而不是他们使用该信息的错误:-)
经典示例是 setter 和 getter。您可能认为您可以将温度变量本身公开在一个类中,以便用户可以执行以下操作:
但是,如果您希望以后在您询问温度时实际上可以从气象局网络抓取信息,该怎么办?如果您一开始就封装了信息,那么调用者就会这样做:
并且您可以根据需要更改该方法的实现。您唯一需要保留的是 API(函数名称、参数、返回类型等)。
有趣的是,它不仅仅存在于代码中。某些大公司会在他们的文档中添加以下短语:
这使他们能够提供客户想要的东西(额外的信息),但不会让他们永远支持它。
Basically, yes, it's to prevent people from screwing with things.
Encapsulation (information hiding) is the term you're looking for.
By only publishing the bare minimum of information to the outside world, you're free to change the internals as much as you want.
For example, let's say you implement your phone book as an array of entries and don't hide that fact.
Someone then comes along and writes code which searches or manipulates your array without going through your "normal" interface. That means that, when you want to start using a linked list or some other more efficient data structure, their code will break, because it's used that information.
And that's your fault for publishing that information, not theirs for using it :-)
Classic examples are the setters and getters. You might think that you could just expose the temperature variable itself in a class so that a user could just do:
But, what if you wanted to later have it actually web-scrape information from the Bureau of Meteorology whenever you asked for the temperature. If you'd encapsulated the information in the first place, the caller would just be doing:
and you could change the implementation of that method as much as you want. The only thing you have to preserve is the API (function name, arguments, return type and so on).
Interestingly, it's not just in code. Certain large companies will pepper their documentation with phrases like:
That allows them to deliver what the customer wants (the extra information) but doesn't lock them in to supporting it for all eternity.
主要原因是,作为库开发人员,您可以确保没有人会使用您不想维护的部分代码。
每段公共代码都可以,并且不可避免地会被您的客户使用。如果您后来发现您的设计实际上很糟糕,并且 2.0 版本应该写得更好,那么您就会意识到您的付费客户实际上希望您保留所有现有功能,并且您必须以维持向后兼容性为代价制作更好的软件。
通过将尽可能多的代码设为私有,您就毫无保留地声明此代码与任何人无关,并且您可以并且将能够随时重写它。
The main reason is that you, the library developer, have insurance that nobody will be using parts of your code that you don't want to have to maintain.
Every public piece of your code can, and inevitably will get used by your customers. If you later discover that your design was actually terrible, and that version 2.0 should be written much better, then you realise that your paying customers actually want you to preserve all existing functionality, and you're locked in to maintaining backwards compatibility at the price of making better software.
By making as much of your code as possible private, you are unreservedly declaring that this code is nobody's business and that you can and will be able to rewrite it at any time.
这是为了防止人们搞砸事情 - 但从安全角度来看不是这样。
相反,它的目的是允许您的类的用户只关心
public
部分,让您(作者)可以自由地修改实现(private
),而不必担心破坏别人的代码。例如,大多数编程语言似乎将
String
存储为char[]
(字符数组)。如果由于某种原因发现节点链表(每个节点包含一个字符)性能更好,则可以切换使用数组的内部实现,不会(理论上)使用 <代码>字符串类。It's to prevent people from screwing with things - but not from a security perspective.
Instead, it's intended to allow users of your class to only care about the
public
sections, leaving you (the author) free to modify the implementation (private
) without worrying about breaking someone else's code.For instance, most programming languages seem to store
String
s as achar[]
(an array of characters). If for some reason it was discovered that a linked list of nodes (each containing a single character) performed better, the internal implementation using the array could be switched, without (theoretically) breaking any code using theString
class.它是向使用你的对象的任何人(你,其他人)提供清晰的代码契约......将“如何使用它”与“它如何工作”分开。这称为封装。
顺便说一句,至少在 .NET 上(可能也在其他平台上),对于真正想要访问对象的私有部分的人来说并不难(在 .NET 中,使用反射)。
It's to present a clear code contract to anyone (you, someone else) who is using your object... separate "how to use it" from "how it works". This is known as Encapsulation.
On a side note, at least on .NET (probably on other platforms as well), it's not very hard for someone who really wants access to get to private portions of an object (in .NET, using reflection).
以计数器为例。夜总会保镖手里拿着的东西,可以让他出拳更用力,也可以统计进出夜店的人数。
现在事情是这样定义的:
如您所见,没有用于 count 的 setter/getter,因为我们不希望此类的用户(程序员)能够调用 myCounter.setCount(100),甚至更糟糕的是 myCounter.Count -= 10;因为这不是这个东西的作用,每个人进入时它都会上升一,每个人离开时它都会下降。
take the typical example of a counter. the thing the bodyguard at your night club is holding in his hands to make his punch harder and to count the people entering and leaving the club.
now the thing is defined like this:
As you can see, there are no setters/getters for count, because we don't want users (programmers) of this class, to be able to call myCounter.setCount(100), or even worse myCounter.Count -= 10; because that's not what this thing does, it goes up one for everyone entering and down for everyone leaving.
对此有很多争论的余地。
例如...如果很多 .Net Framework 是私有的,那么这将防止开发人员把事情搞砸,但同时它也会阻止开发人员使用该功能。
以我个人的观点,我更倾向于公开方法。但我建议使用 Facade 模式。简单来说,您有一个封装复杂功能的类。例如,在.net框架中,WebClient是一个Facade,隐藏了复杂的http请求/响应逻辑。
另外......保持类简单......并且你应该有很少的公共方法。这是比拥有大量私有方法的大型类更好的抽象
There is a scope for a lot of debate on this.
For example ... If a lot of .Net Framework was private, then this would prevent developers from screwing things up but at the same time it prevents devs from using the funcionality.
In my personal opinion, I would give preference to making methods public. But I would suggest to make use of the Facade pattern. In simple terms, you have a class that encapsulates complex functionality. For example, in the .net framework, the WebClient is a Facade that hides the complex http request/response logic.
Also ... Keep classes simple ... and you should have few public methods. That is a better abstraction than having large classes with lots of private methods
了解对象如何“组合”起来,请观看 YouTube 上的此视频
http://www.youtube.com/watch?v=RcZAkBVNYTA&list=PL3FEE93A664B3B2E7&index=11&feature=plpp_video
It is useful to know how an object s 'put together' have a look at this video on YouTube
http://www.youtube.com/watch?v=RcZAkBVNYTA&list=PL3FEE93A664B3B2E7&index=11&feature=plpp_video