Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are private methods as bad as public fields? [closed]

Tags:

java

oop

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.

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 externed 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.

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:

  • Are there any standard Java guidelines limiting the use of private methods? (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).
  • 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. Are there any widely-used design patterns that can help me reduce the number of private methods in my classes?)
like image 680
John Gowers Avatar asked Dec 02 '22 21:12

John Gowers


1 Answers

Are there any standard Java guidelines limiting the use of private methods?

No.

On the contrary - what can be private should be private. A lot of private methods in a class are in no way a bad practice (as long as the class itself is not too long). The interface should only offer the methods usable by outer classes. What happens inside, privately, is no one's bussiness.

It is actually much better to have one short public method and a few private ones (even if they are not called repeatedly), because it increases readability and makes a high-level overview over the one public method possible. If you have a public method which can be divided into multiple self-standing parts and you can name the parts, then do it. With a private method.

like image 158
Petr Janeček Avatar answered Dec 23 '22 00:12

Petr Janeček