什么时候写私有方法,而不是受保护的方法? [英] When do you write a private method, versus protected?

查看:100
本文介绍了什么时候写私有方法,而不是受保护的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在写一个类,什么时候将方法设为私有而不是受保护?换句话说,我如何事先知道客户端程序员从不永远不需要重写方法?如果是外部考虑的东西,例如数据库连接?

解决方案

publicprotected方法形成对象的接口",对于使用(委托)您的类的开发人员,public形成;而对于希望通过子类扩展对象功能的开发人员.

请注意,即使您的类将被子类化,也不必提供protected方法.

publicprotected接口都需要仔细考虑,特别是如果这是供您控制之外的开发人员使用的API时,因为对接口的更改可能会破坏对现有接口的工作方式进行假设的程序. /p>

private方法纯粹是对象的作者,可以随意重构,更改和删除.

默认情况下,我会使用private,如果您发现需要公开更多方法,请仔细考虑如何使用它们-尤其是它们是虚拟的时-如果将它们完全替换为,会发生什么情况.另一个开发人员提供的任意替代功能-您的课程仍然可以使用吗?然后设计一些合适的protected,这对开发人员将对象子类化(如果需要)很有用,而不是暴露现有功能.

If I'm writing a class, when do I make a method private, versus protected? In other words, how I can know in advance that a client programmer would never ever need to override a method? In a case where it's something that has external considerations, like a database connection?

解决方案

public and protected methods form the 'interface' to your object, public for developers using (delegating to) your class, and protected for developers wishing to extend the functionality of your object by subclassing it.

Note that it's not necessary to provide protected methods, even if your class will be subclassed.

Both public and protected interfaces need careful thought, especially if this is an API to be used by developers outside your control, since changes to the interface can break programs that make assumptions about how the existing interface works.

private methods are purely for the the author of the object, and may be refactored, changed and deleted at will.

I would go for private by default, and if you find you need to expose more methods, have a careful think about how they will be used - especially if they are virtual–what happens if they are replaced completely with an arbitrary alternative function by another developer–will your class still work? Then design some appropriate protected which are useful for developers subclassing your object (if necessary), rather than exposing existing functions.

这篇关于什么时候写私有方法,而不是受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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