Private Methods Over Public Methods

2019-01-21 09:19发布

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

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.

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?

Here is a small example:

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?

7条回答
混吃等死
2楼-- · 2019-01-21 10:09

The only reason I could think of why private methods are useful is because it helps you from writing duplicate code.

In addition to consolidating duplicate code (often expressed as "Don't Repeat Yourself" or "DRY"), use of private methods can also help you to structure and document your code. If you find yourself writing method which does several things, you may wish to consider splitting it into several private methods. Doing so may make it clearer what the inputs and outputs for each piece of logic are (at a finer granularity). Additionally, descriptive method names can help supplement code documentation.

查看更多
登录 后发表回答