Note that there are some explanatory texts on larger screens.

plurals
  1. POAre private methods as bad as public fields?
    text
    copied!<p>Please excuse the provocative question title. It's well known that you're never supposed to use public fields in a Java program (except in struct-like classes, which you're supposed to avoid anyway). But people talk far less about the other side of the coin - private methods. </p> <p>The way I see it is this: if you have private methods, then you are writing locally procedural code. There is essentially no difference between a Java class with private fields and a few public methods which call a number of private methods, and a C module with global variables and some functions, some of which are <code>extern</code>ed elsewhere (apart from the fairly big difference that you can't instantiate a C module). Given that a lot of the people who care most about good Java practice take the view that you should stay as far out of the procedural rut as possible, I'm surprised that there aren't more guidelines limiting the use of private methods. </p> <p>Note that I don't want to suggest that anybody thinks that private methods should never be used (or that they're actually as bad as public fields). But here are my questions, which I've tried to make as objective as possible: </p> <ul> <li><strong>Are there any standard Java guidelines limiting the use of private methods?</strong> (An example of a standard guideline is 'no public fields' - though you could argue that it's a matter of opinion, it's pretty much universally accepted to be good practice not to use public fields). </li> <li>How do I get round using private methods? (For example, one can get round using public fields by declaring them private and using public get/set methods. If I have a class with lots of private methods in it, I imagine that I ought to be creating a new class to hold them. But if I do that, then I run the risk of writing a Java class that is never instantiated and behaves exactly like a C module. <strong>Are there any widely-used design patterns that can help me reduce the number of private methods in my classes?</strong>)</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload