公共方法的私有方法 [英] Private Methods Over Public Methods

查看:103
本文介绍了公共方法的私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查 StringTokenizer.java 类,我想到了一些问题。

I was examining the StringTokenizer.java class and there were a few questions that came to mind.

我注意到其他类使用的公共方法调用了一些完成所有工作的私有方法。现在,我知道OOD的原则之一就是尽可能多地隐藏并隐藏所有实现细节。我不确定我是否完全理解这背后的逻辑。

I noticed that the public methods which are to be used by other classes invoked some private method which did all of the work. Now, I know that one of the principles of OOD is to make as much as you can private and hide all of the implementation details. I'm not sure I completely understand the logic behind this though.

我知道将字段设为私有以防止无效值存储在其中非常重要(只是众多原因之一)。然而,当谈到私人方法时,我不确定它们为何如此重要。

I understand that it's important to make fields private to prevent invalid values being stored in them (just one of many reasons). However, when it comes to private methods, I'm not sure why they're as important.

例如,在 StringTokenizer 类的情况下,我们不能只放置所有的实现公共方法里面的代码?它如何对使用这些方法的类产生影响,因为这些方法的API(即调用这些公共方法的规则)将保持不变?我能想到为什么私有方法有用的唯一原因是它可以帮助你编写重复的代码。例如,如果所有公共方法都做了同样的事情,那么您可以声明一个执行此任务的私有方法,并且可以由公共方法使用。

For example, in the case of the StringTokenizer class, couldn't we just have put all of the implementation code inside the public methods? How would it have made a difference to the classes which use these methods since the API for these methods (i.e. the rules to call these public methods) would remain the same? The only reason I could think of why private methods are useful is because it helps you from writing duplicate code. For example, if all of the public methods did the same thing, then you can declare a private method which does this task and which can be used by the public methods.

其他问题,在私有方法中编写实现而不是公共方法有什么好处?

Other question, what is the benefit of writing the implementation in a private method as opposed to a public method?

这是一个小例子:

public class Sum{

    private int sum(int a, int b){
        return a+b;
    }

    public int getSum(int a, int b){
        return sum(a,b);
    }
}

Vs ...

public class Sum{

    public int getSum(int a, int b){
        return a+b;
    }
}

第一个样本如何更有益?

How is the first sample more beneficial?

推荐答案

为了添加内容,私有方法总是可以安全地更改,因为您确定只能从自己的类中调用,没有外部类可以调用私有方法(他们甚至看不到它)。

In order to add something, a private method can ALWAYS be changed safely, because you know for sure that is called only from the own class, no external classes are able to call a private method (they can't even see it).

所以有一个私有方法总是很好,因为你知道没有有关更改它的问题,即使您可以安全地向该方法添加更多参数。

So having a private method is always good as you know there is no problem about changing it, even you can safely add more parameters to the method.

现在想想一个公共方法,任何人都可以调用该方法,所以如果你添加/删除一个参数,你还需要更改所有对该方法的调用。

Now think of a public method, anyone could call that method, so if you add/remove a parameter, you will need to change also ALL the calls to that method.

这篇关于公共方法的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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