Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most common way of ordering Java methods?

Ordering Java methods is probably the least important code style issue ever, but I'm trying to develop a code style as similar to what most people do as possible. It's by far the most popular approach to first declare all fields and then all methods, so I'll only ask about methods.

Now I'm wondering how to order Java methods. I can think of two sensible basic approaches:

  1. Order methods by visibility (i.e. first public, then protected, then private or the other way around)
  2. Order methods by dependency (i.e. if method a() calls method b(), put them as closely together as possible)

As far as I see it, the second approach seems to be more popular by far. Nonetheless, in both cases there is the question of the direction, and it is not as clear what most people use. In the second approach, you can either place a() above or below b(). I think placing b() above a() (and eventually main() at the bottom of the class file) is more common in C, not sure about C++. The other way around is IMO better for reading, from top to bottom. What's the most common approach in Java? Any special rules about static fields/methods?

like image 791
JRoberts Avatar asked Feb 25 '23 20:02

JRoberts


2 Answers

I gave up on "logically" when I discovered that "logically" is a relative term; what is logical for one programmer is not always logical for a different programmer. If I have to learn what your "logically sorted" means, then it fails as a "logically sorted" technique.

I prefer to alphabetize my methods and my data-members. I believe that alphabetical, psuedo-linear search the "natural" technique for people who think in English. For example, attempt to logically sort any of the following: an encyclopedia, a phone book, a contact email list.

The classic argument against the alphabet is [spoken with soviet era Russian accent] "Ve haf IDE for alfabet searchz! Is nots needed in kode!" My reply to such arguments is a varient of "Yes, Mr. Stalin. But not everybody uses an IDE to view code. Some people still use (and like) vi. I may not be one of those people, but I know they exist. Other people have learned that the page-up and page-down keys work nicely when the code is organized alphabetically."

like image 88
DwB Avatar answered Mar 03 '23 06:03

DwB


I think adding getters, setters, equals, hashCode and toString at the bottom is useful since that's usually not something a developer cares a lot about once it's in place.

like image 37
AHungerArtist Avatar answered Mar 03 '23 06:03

AHungerArtist