This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
Greetings, fellow ranchers. While perusing the internet for help for a solution to a programming exercise, I came across two almost identical solutions. The first example is similar to the solution provided in my textbook. The second example is very different from anything I have seen so far. Why, in the second example, do they go to the extra trouble to have a public AND a private method?
The author did talk about having private instance methods and public accessor/mutator methods. Is this a similar issue?
Example One (similar to what I've been learning so far, in that it only has a public method)
Example Two (very different from the text I'm using SO FAR because it has a publicandprivate method with the same name)
It's broken up into two methods for logical/design reasons. One method just gets the max depth of the whole tree. The other gets the max depth from a given node. They apparently decided that outside users of that class would only need to ever find the max depth of the tree, so there was no reason to expose the other method to them.
These are recursive methods which traverse a tree. Recursive means that in order to find the solution, the method calls itself. In the first example, the method takes Node as a parameter. So each time it encounters a new Node, it calls itself passing the Node as the argument. In the second example there is no parameter, we just want to find out how deep the tree goes. But for recursive walking of a tree to work, we have to pass a node in. So we create an auxiliary private method that takes the Node parameter.
Ken Austin wrote:
Jeff, is that that a "best practice?" Should I incorporate that in my code?
Breaking a method down into logical, simpler steps is a best practice, up to a point. In this case there is a sensible division between the jobs of the two methods, so I would say it was a good choice here. You should incorporate this practice into your code in cases where it would foster code reuse or where a potentially "too long" method would benefit from being broken down into logical, simpler steps.
Making a method that is a "sub-step" (not to be confused with this) of another method private when there is no reason in your design for external users of the class to call the directly is a best practice. I don't know enough about the overall requirements and design to comment on whether it was a good choice here, but if this is just an isolated code snippet provided for the purposes of demonstration, there is no right/wrong to it here. You should incorporate this practice into your code in cases where your design suggests no reason for a "sup-step" method to be called by external users of the clas.