开发者

Java declarations (ordering)

开发者 https://www.devze.com 2022-12-25 07:11 出处:网络
In Java, what\'s generally the most accepted way to organize a class in terms of the order in which declared data members and methods should be listed in the class file, keeping in mind the following

In Java, what's generally the most accepted way to organize a class in terms of the order in which declared data members and methods should be listed in the class file, keeping in mind the following and anything else you can think of for each one:

  • its visibility
  • whether it's a constructor, method, or member
  • if it's a method, does it overload, or over开发者_开发技巧ride other method(s)?


I've found that the conventions in Code Conventions for the JavaTM Programming Language to be quite suitable. Chapter 3 answers this question.

Mostly it ignores visibility or whether it is an overloaded function etc.

It is simply in order:

  • Class (static) variables
  • Instance variables
  • Constructor
  • Methods

A more rigorous approach could be taken, but I do not see a strong argument in its favor.


There are suggested best practices and the ones Kris mentions are pretty much "the" standard, with Inner Classes at the bottom of that list.
That said, if you are using Intellij IDEA (there is a free Community version) there is a plug-in called Rearranger, that lets you specify all this and enforce it and more importantly refactor existing code to be what you think it should be.


You could follow the recommendation used by the Google project GWT, if you want. It's based on the standard Java code conventions from Sun. It adds some strict rules on ordering, also concerning visibility modifiers etc.:

http://code.google.com/webtoolkit/makinggwtbetter.html#codestyle


Eclipse (and, I'm sure, other IDEs) will automatically order declarations (Source -> Sort Members), with options for types and visibility. Overloading and overriding aren't available, at least in Eclipse. So I would say establish a convention that includes type and maybe visibility, but not overload/override status, then configure your team's IDE to impose that convention. Automatable - and automated - standards are much easier for the team to adhere to.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号