最好使用私有方法或受保护的方法? [英] Best to use Private methods or Protected methods?

查看:49
本文介绍了最好使用私有方法或受保护的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的许多PHP项目中,我最终得到的类都具有我不打算扩展的非公共功能.

In a lot of my PHP projects, I end up with classes that have non-public functions that I don't intend to extend.

最好将它们声明为受保护的还是私有的?

Is it best to declare these as protected, or private?

我可以用两种方式看到参数-将它们设为私有是一种更为保守的方法,但是可以争论的是,如果我希望扩展该方法,并且可以清楚地说明哪些方法可以通过扩展,则可以在以后对它们进行保护.基类.

I can see arguments both ways - making them private is a far more conservative approach, but it can be argued that they could be made protected later if I want the method to be extended and it makes it clear which methods are extended by base classes.

另一方面,是否使用私有方式反社会,因为这会阻止理论上的未来开发人员扩展我的代码而不进行修改?

On the other hand, is using private somehow antisocial, in that it impedes a theoretical future developer from extending my code without modification?

推荐答案

我的本​​能是将它们设为私有,直到您需要其他条件为止.

My instinct is to keep them private, until you need them to be otherwise.

有人认为(很遗憾,我把链接放错了位置)使方法私有化是反社会的,与使它们最终化"的方式几乎一样,因为这是人们如何使用您的代码的完全独裁性.

It has been argued (sadly I've misplaced the link) that making methods private is antisocial, in much the same way as making them 'final', in that it's fairly dictatorial about how people may use your code.

但是,我不相信,并且同意只应公开真正需要的内容.库或工具箱是个例外,您将期望用户希望以您从未想到的方式扩展(一般意义上)您的代码.在这种情况下,可以将使精心选择的方法得到保护的做法视为提供了灵活性.

I'm not convinced, however, and agree that you should expose only what you really need to. The exception would be a library or toolkit, where you'll expect users to want to extend (in the general sense) your code in ways which you would never foresee. In which case making well-chosen methods protected can be seen as providing flex-points.

这篇关于最好使用私有方法或受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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