Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

java - Private Methods Over Public Methods

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...