|
Re: JUnit FAQ suggests private methods bad design?
Paul Carey wrote:
> <JUnit faq>
> How do I test private methods?
> Testing private methods may be an indication that those methods should
> be moved into another class to promote reusability.
> But if you must...
> </JUnit faq>
An alternative to private methods does exist.
Instead of making a method private, you can
always create a new class whose instance you
store in a private member/instance -variable.
Your main class can then send message to this
private data object, but if you don't ever
return it from any method, no other object can.
Thus you have "privacy without private methods".
This pattern may be preferable to "private
methods" in many cases, since it adds more
structure and reusability into your program.
The class of the private data-object can in
fact be used separately in different situations
since it does have its *own* set of public methods.
And unlike private methods, it can be subclassed
as well.
So, I would argue: "Private methods considered
unnecessary".
-Panu Viljamaa
>
> Typically I try to code to an interface, have a class implement that
> interface and if possible never expose more public methods than are in
> the interface it implements. But my public methods often invoke a
> number of private methods. It is these methods that usually do the
> grunt work of my classes. I can change the private methods as I see
> fit and never need to worry about breaking other classes. Fewer
> methods to support (public methods) means fewer dependencies means
> fewer things to go wrong. I find this to be good way to program, but
> the answer in the FAQ would seem to suggest it's not. But I'm not sure
> agree with moving a private method to another class to promote
> reusability. If certain data is only available via a private method, a
> client that requires this data can invoke a public methods, receive a
> high level object and extract the data it requiers from the high level
> object. Granted this means a little more work for the client, but
> assuming the high level object the client receives has a well defined
> interface, I see that approach as promoting stability. I was wondering
> what other people's thoughts are on this issue.
> Many thanks
> Paul
|