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:
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?
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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With