-1

This question stems from several related questions, and is somewhat reasking the first which doesn't seem to have a clear answer to the OP's main question:

I very clearly understand the purpose of private methods, but I am having difficulty thinking of an example where having the function's implementation in a private method wouldn't cause problems for an API consumer, but placing the implementation directly in the public method would. This is a common practice in Java's APIs.

I'm basically re-asking the first question above because I didn't read an answer that solidifies my understanding. Taking the same 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);
    }

}

What is the benefit of using the private sum function, rather than just placing the result directly in the public function?

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

Perhaps this isn't the best example, but I very much welcome more complex or real-world examples as well.

Again, I understand that placing the implementation in a private method hides the implementation and allows for re-use and is overall a better practice for future additions. However,

  • How does not having it in a private method have the ability to disrupt the API's consumers?
  • Should all public methods be created this way (always place the implementation in a private method), or where is the line drawn?
Dewick47
  • 171
  • 11
  • 2
    The sum example seems pointless. Do you have a real-world case? – shmosel Oct 24 '18 at 19:52
  • 2
    It is useful if you want other methods in `Sum` to be able to use the original implementation of `getSum` even if subclasses can override it. – Andy Turner Oct 24 '18 at 19:56
  • I don't have a real-world case, which is why I don't understand the argument of disrupting any code calling the public function. The sum example is likely much too simplistic to show this, but not having an actual example is why I'm asking the question anyway. – Dewick47 Oct 24 '18 at 20:01
  • When I look back at most of Java's data structure implementations, such as HashMap and LinkedList, the private methods being called are typically just factored out for reuse. That's why I'm confused about the disrupting the caller argument. – Dewick47 Oct 24 '18 at 20:03

1 Answers1

0

Putting implementation in private methods as you showed does not make any difference.

I believe this question mistakened the relation between "interface <-> implementation of a method" with "public method <-> private method".

The thing that matters is separating interface from implementation. Consumer only sees the interface. Function provider picks / injects the appropriate implementation.

Ben Hu
  • 33
  • 1
  • 4