David Bullock
David Bullock

Reputation: 6254

When should I declare fields after methods in the source of a Java class?

Some Java coding standards recommend declaring the fields of a class after all the methods. Fields are an implementation detail, and are less important than any public method signatures, the theory goes.

However, I have - so far - found it difficult to adopt this practice. I find that a quick glance of the member fields is a useful key to understanding how a class is approaching its responsibilities - which I generally already understand from the interfaces the class implements. It is the methods which are the 'implementation details' when I'm reading the source. And the source is to be laid-out for easy reading, right?

Like any advice, it's important to understand the tradeoffs. I'm pretty clear on what I'm missing when I declare the fields last. But can anyone enumerate what I really gain?

Upvotes: 1

Views: 393

Answers (1)

Andy Thomas
Andy Thomas

Reputation: 86391

Some things to consider:

  • Your Java source file contains both interface and implementation. Both may be important to a reader.
  • Anyone interested in only the public interface can look at the Javadocs for the class.
  • Code generated by your Java IDE will likely default to fields before methods. New methods may be created at the bottom, which would shift fields-at-the-bottom into fields-in-the-middle.

Upvotes: 2

Related Questions