什么时候应该将方法设为私有? [英] When should methods be made private?

查看:128
本文介绍了什么时候应该将方法设为私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候,我不确定是否应将某个特定方法设为私有.例如,我现在正在构建一个类,该类负责生成报告.此类有一个buildReport方法和几个为buildReport收集必要数据的方法.

There are lots of times where I'm not sure whether a particular method should be made private or not. For example, I'm building a class right now, which, is responsible for generating a report. This class has a buildReport method and several methods which collect the necessary data for buildReport.

// single public method
// uses a set of helper methods
public buildReport()

// helper methods
private avgSurveyTime()
private fetchVendors()
private fetchSendCounts()
private ...

我正在辩论是否应该公开这些辅助方法.目前,我真正打算在外部进行呼叫的唯一方法是buildReport().但是,仅用fetchVendors()等获取供应商列表可能会很有用.

I'm debating whether I should make these helper methods public. The only method I really plan on calling outside at the moment is buildReport(). However, it might be useful to get just a list of the vendors with fetchVendors() etc.

我对此有两种思路:您总是可以尽可能少地进行揭露. (在这种情况下,我的很多类都只有一个公共方法),或者您可以公开所有可能对类用户有用的东西.

I see two schools of thought on this: You can always expose as little as possible. (In which case, many of my classes would only have one public method) OR you can expose all you can that might be useful to the user of the class.

在确定何时应该公开/私有方法时是否有良好的经验法则?

Is there a good rule of thumb to use for deciding when methods should be made public/private?

推荐答案

我遵循的唯一规则是尽可能少地公开.

The only rule I follow is to make as little as possible public.

这样看.您以后总是可以将某些内容公开-它不会破坏任何现有代码.试图使公开的私有内容最终可能破坏许多现有代码.

Look at it this way. You can always make something public later on - it won't break any existing code. Trying to make something private that was public could well end up breaking a lot of existing code.

如果某人想要从您的班级获得更多功能,那么他们可以提出请求,您可以公开他们所需要的东西.他们可能会想要的东西与您已经拥有的东西有细微的差别,因此您需要一个新的界面.

If someone wants more functionality from your class then they can make the request and you can expose what they need. Chances are that they'll want something that's subtly different to what you already have anyway so you'll need a new interface.

这篇关于什么时候应该将方法设为私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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