- In Java, should private helpers go above or below public methods? [closed]
- 5 Answers 5
- Can Methods be Declared in Any Order in a Java Class?
- Can Methods be Declared in Any Order in a Java Class?
- How to Declare Methods in Any Order in a Java Class?
- Conclusion
- About the author
- Syed Minhal Abbas
- Most human-friendly way to order class method definitions?
- 4 Answers 4
In Java, should private helpers go above or below public methods? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
I’ve noticed that a coworker and I have opposite practices regarding the ordering of methods in our Java classes. One of us begins a class with its major public methods, and then put all of the private helpers afterwards. The other one of us makes sure that public methods are at the very end. Clearly, this is just a style issue and there is no right answer. However, before we decide that this matter is just another Yooks vs Zooks fight and just pick one or the other arbitrarily, I was wondering if perhaps there was a standard Java style guide recommendation or some practical reason why one approach is better than the other.
@KilianFoth — This question was asked 3 months earlier and has more answers. Wouldn’t that make the question in question a duplicate of this question?
5 Answers 5
While it does come down to preference normally, you should certainly try to adhere to a common standard within your organization. So whatever you decide, pick a standard and universally adopt it.
As for which to choose, if you were to follow the suggestions as offered in Clean Code, you would be able to read down the file from top to bottom like a newspaper article, which would naturally suggest that helper methods appear after the methods they are helping. This would lead to maximum readability of the code structure. So if you were to have
Your file would be structured as
public void doSomething() < >private void helpMe() < >private void helpMeAgain()
Another side effect of this is that you discover your helpers have their own helpers, and it helps you figure out what you really have is another class living within your file, and you can cleanly refactor to extract it to its own class since those methods are already grouped together in order. But that’s a secondary benefit.
Glad you said this or else I would have. I asked Bob Martin himself how he orders things if 2 methods each use a 3rd method. In that case he puts the 3rd below the other two.
Your example doesn’t show it, but this leads to public methods mixed in among the private methods. I use this technique, but often then I feel torn and want to boost all the public methods to the top, because there is also much to be said for reading the public interface easily.
@Sean, well, I would typically try to limit either the public API of my class, or leave it as a facade if appropriate but then shove the implementation helpers down into collaborators. Test, refactor, extract, repeat. But it of course depends on how far you want to go. I prefer my classes small.
Public methods are the interface of the class. Someone interested in using your class will only care about the interface. From the perspective of a class user, it would be useful to have the public methods first to reduce scrolling.
In C and C++, helper methods are often put first because then you don’t need a declaration. A lot of people carried that habit over into other languages where it doesn’t matter.
I prefer the public methods on top because usually when I open a file I’m looking for its public interface. I don’t want to have to scroll past all the implementation details. It also happens to be the most popular style I’ve seen, so there’s that to be said for convention.
I like order of methods in a class to be based on readability and context, not visibility.
i.e. an ‘open’ method probably belongs before a ‘close’. If two public methods ‘a’ and ‘b’ call a private ‘c’, and they’re the only ones calling it — then I like ‘c’ to be next to them.
I don’t think a convention of method ordering based on visibility is a good thing.
I tend to prefer seing my classes where members are listed in order of importance/visibility (here by importance I mean that have direct impact on the public interface).
Thus private functions have a tendency to be pushed down.
There are exceptions to this where I will also tend to group similar functionnalities together so it is still possible to find small private functions intermingled with the public stuff.
This is, as you said, a matter of taste.
However when working on code that is not mine I will try nd follow whatever conventions that is used in the project.
One nice way I found to keep track of this is to (assuming here you work with Eclipse) create a code formatting configuration and export it with the project source and commit it to source control. That way the latest and greatest in code convention for the project is a mere few clicks away to setup and making a habbit of CTRL-SHIFT-F jufore you commit will prevent a lot of arguments.
Added bonus of using automatic formatters is that you can do things in whatever convention that makes you happy and just format the code before commit. YMMV depending on said convention and formatting tool.
Can Methods be Declared in Any Order in a Java Class?
Java is an object-oriented programming language that allows users to define classes to represent real-world objects. Each class can contain one or more methods that define its behavior. The purpose of declaring methods in any order in a Java class is to provide flexibility and readability to the code. By allowing methods to be declared in any order, Java gives developers the freedom to organize their code in a way that makes sense for their program’s logic and structure.
This article will demonstrate the following content:
Can Methods be Declared in Any Order in a Java Class?
Yes, in Java, methods can be declared in any sequence within a class. The Java compiler does not impose any restrictions as significant as method declarations within a class. Users can declare methods in any order that makes sense for your program’s logic and organization. However, it is common practice to group related methods together for better readability and maintainability of the code.
Another thing to consider is that Java programs are compiled in multiple passes. The first pass verifies for any syntax errors. During the second pass, the compiler resolves any references to other classes, methods, or variables. As long as all the methods are properly defined and there are no syntax errors, the compiler can compile the class regardless of the order of method declarations.
How to Declare Methods in Any Order in a Java Class?
Here is an example of declaring methods in a different order in a Java class:
// instance variables
private String name ;
private int age ;
// constructor
public Person ( String name, int age ) {
this . name = name ;
this . age = age ;
}
public void setName ( String name ) { // setter method for name
this . name = name ;
}
public String getName ( ) { // getter method for name
return name ;
}
public int getAge ( ) { // getter method for age
return age ;
}
public void setAge ( int age ) { // setter method for age
this . age = age ;
}
// method to check if the person is eligible to vote
// method to check if the person is eligible to vote
public boolean canVote ( ) {
return age >= 18 ;
}
// main method
public static void main ( String [ ] args ) {
Person person = new Person ( «John» , 25 ) ;
System . out . println ( person. getName ( ) + » is » + person. getAge ( ) + » years old.» ) ;
System . out . println ( person. getName ( ) + ( person. canVote ( ) ? » can vote.» : » cannot vote.» ) ) ;
person. setAge ( 15 ) ;
System . out . println ( person. getName ( ) + » is now » + person. getAge ( ) + » years old.» ) ;
System . out . println ( person. getName ( ) + ( person. canVote ( ) ? » can vote.» : » cannot vote.» ) ) ;
person. setName ( «Jane» ) ;
System . out . println ( person. getName ( ) + » is » + person. getAge ( ) + » years old.» ) ;
System . out . println ( person. getName ( ) + ( person. canVote ( ) ? » can vote.» : » cannot vote.» ) ) ;
}
}
The explanation of the above code is given below:
- A class called Person that represents a person’s name and age. We have declared instance variables for name and age, followed by a constructor to initialize them.
- Next, we have declared setter and getter methods for name and age, which allows us to set and get the values of these variables from outside the class.
- After that, we have declared a method called canVote() that returns true if the person is eligible to vote (age 18 or above), and false otherwise.
- Finally, we have declared the main method, where we create an instance of the Person class, set, and get its name and age using the setter and getter methods, and check if the person is eligible to vote using the canVote() method.
This shows that Java does not impose any restrictions like method declarations within a class.
Conclusion
Yes, Java methods can be declared in any order within a class. There is no technical limitation to the order of method declarations in a Java class. The purpose of declaring methods in any order in a Java class is to provide flexibility, encapsulation, code reuse, and efficient compilation of the code. It is recommended to group related methods together for better organization and readability.
About the author
Syed Minhal Abbas
I hold a master’s degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.
Most human-friendly way to order class method definitions?
You don’t really expect people to cut/paste code simply to reorder methods. If the IDE does it automatically, then fine. Otherwise, it’s hard to enforce.
4 Answers 4
In some programming languages, order does matter because you can’t utilize things until after they’ve been declared. But barring that, for most languages it doesn’t matter to the compiler. So then, you’re left with it mattering to humans.
My favorite Martin Fowler quote is: Any fool can write code that a computer can understand. Good programmers write code that humans can understand. So I’d say that the ordering of your class should depend on what makes it easy for humans to understand.
I personally prefer the step-down treatment that Bob Martin gives in his Clean Code book. Member variables at the top of the class, then constructors, then all other methods. And you order the methods to be close together with how they are used within the class (rather than arbitrarily putting all public then private then protected). He calls it minimizing the «vertical distance» or something like that (don’t have the book on me at the moment).
The basic idea of «vertical distance» is that you want to avoid making people jump all around your source code just to understand it. If things are related, they should be closer together. Unrelated things can be farther apart.
Chapter 5 of Clean Code (great book, btw) goes into a ton of detail on how Mr. Martin suggests ordering code. He suggests that reading code should work kind of like reading a newspaper article: the high-level details come first (at the top) and you get more detail as you read down. He says, «If one function calls another, they should be vertically close, and the caller should be above the callee, if at all possible.» Additionally, related concepts should be close together.
So here’s a contrived example which is bad in many ways (poor OO design; never use double for money) but illustrates the idea:
public class Employee < . public String getEmployeeId() < return employeeId; >public String getFirstName() < return firstName; >public String getLastName() < return lastName; >public double calculatePaycheck() < double pay = getSalary() / PAY_PERIODS_PER_YEAR; if (isEligibleForBonus()) < pay += calculateBonus(); >return pay; > private double getSalary() < . >private boolean isEligibleForBonus() < return (isFullTimeEmployee() && didCompleteBonusObjectives()); >public boolean isFullTimeEmployee() < . >private boolean didCompleteBonusObjectives() < . >private double calculateBonus() < . >>
The methods are ordered so they are close to the ones that call them, working our way down from the top. If we had put all the private methods below the public ones, then you’d have to do more jumping around to follow the flow of the program.
getFirstName and getLastName are conceptually related (and getEmployeeId probably is too), so they are close together. We could move them all down to the bottom, but we wouldn’t want to see getFirstName at the top and getLastName at the bottom.
Hopefully this gives you the basic idea. If you’re interested in this kind of thing, I strongly recommend reading Clean Code .