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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…