何时将方法声明为私有
我正在寻找具体且准确的规则来确定如何声明方法的可见性。这与语言无关,它适用于标准 OOP 语言。
I am looking for specific and exact rules to determine how a method's visibility can be declared. This is not language agnostic, it applies to the standard OOP languages.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
一个值得遵循的好规则是:
从
private
开始,并在需要时使它们更易于访问。A good rule to follow would be:
Start with
private
and make them more accessible as the need arises.基本上:
getState()
这样的东西适合这里。changeState(...)
。一般来说,这与对象内容的实际更改有关 - 也许您将有一个公共setX(int x)
,它只调用私有setXInternal(int x)
,即这样你就可以进行额外的类型检查/安全/等等。为了安全起见,您最好将所有内容设为私有,除非必须这样做。Basically:
getState()
would fit here.changeState(...)
. Generally this relates to the actual alteration of an object's contents - maybe you'll have a publicsetX(int x)
that just calls the privatesetXInternal(int x)
, that way you can have extra type-checking/safety/etc. To be safe you might as well make everything private until it has to be otherwise.任何类/对象都有:
1.它所做的事情(行为)
2. 它是如何做的(实现)
世界关心你的对象的行为。它不应该(通常)关心它是如何在幕后实现这种行为的。将实现细节保密,并公开行为。
With any class/object there are:
1. things it does (behaviours)
2. how it does them (implementation)
The world cares about the behaviour of your object. It shouldn't (often) care about how it achieves this behaviour under the hood. Keep implementation details private, and expose behaviours.
任何不直接定义特定对象的行为但在对象行为的实现过程中有用的操作都是私有成员函数的候选者。
Any kind of operation which does not define behaviour of particular object directly but is useful during implementation of object's behaviour is a candidate for private member function.
我认为 public、protected 和 private 关键字的用处只是让代码更加清晰。
因此,您可以使用 public 作为类的 API,使用 private 来明确如何不扩展类,并在其他情况下使用 protected。
常见的务实方法是永远不要使用私有的,而只使用公共的或受保护的。
I think the helpfulness of the public, protected and private keywords is just to make the code more clear.
So you would use public for the API of a class, private to make it clear how to do NOT extend a class and protected in every other case.
A common pragmatic approach is never use private and to use just public or protected.
对于属于公共 API 一部分的事物,公共。
保护您希望子类能够调用的非公共函数。
如果您不希望子类使用该方法(或者甚至不知道它的存在),则为私有。
在 C、C++ 和 C# 中,如果您希望子类能够重写方法,请不要忘记将方法标记为 virtual。
Public for things that are part of the public API.
Protected for non-public functions that you want subclasses to be able to call.
Private if you don't want subclasses mucking around with said method (or to even know of its existence).
In C, C++, and C# don't forgot to mark a method virtual if you want a child class to be able to override it.