0

I have come to the question: what is the most preferred way of placing methods? I mean, should first declare static methods, then constructors, then public methods, then protected, then private, etc? Is there some kind of convention, like I guess everyone places fields (instance variables) on top of the code. Is there the same policy about methods?

I guess it depends on the language you use. What about Java?

t3rmin41
  • 668
  • 2
  • 8
  • 18
  • 1
    The order in Java is not relevant, as long as they are there. – Stultuske May 08 '15 at 08:03
  • Just be consistent. Ask the rest of your team if you follow some convention. If not, or if you're writing code on your own, pick a convention of your choice (for instance the official Java Code Convention from Oracle) and stick to it. – aioobe May 08 '15 at 08:04

3 Answers3

4

This is somewhat opinion based, but the Google Java Style doc puts it nicely:

The ordering of the members of a class can have a great effect on learnability, but there is no single correct recipe for how to do it. Different classes may order their members differently.

What is important is that each class order its members in some logical order, which its maintainer could explain if asked. For example, new methods are not just habitually added to the end of the class, as that would yield "chronological by date added" ordering, which is not a logical ordering.

https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s3.4.2-class-member-ordering

Most of the code I see in the open source world uses some variation of

  • static fields
  • instance fields
  • constructors
  • methods (instance and static)
  • anonymous classes
Community
  • 1
  • 1
Steve Chaloner
  • 8,162
  • 1
  • 22
  • 38
1

It comes down to team preference, but it is always good to follow convention

epoch
  • 16,396
  • 4
  • 43
  • 71
0

Talking about execution, JVM guarantees the order which we cannot change.manage.

But from code readability point of view , YES ordering does looks good. Following coding standards is what should do.

Static fields -> instance fields/variables

As we know, Static Block is always called once class is loaded, so we should have it.

Then constructors, for object creation, there is no point of writing constructor at the end.

also a good read here as suggested above.

Community
  • 1
  • 1
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • Yes, I'm talking solely about readability. Place of declaration doesn't matter for variables and methods as Java doesn't have "forward reference" problem in class declaration. – t3rmin41 May 08 '15 at 08:10