开发者

Convention for methods declaration in Java

Is there a convention in Java开发者_JAVA技巧 on where to declare fields - before or after methods?


Class layout: see here http://java.sun.com/docs/codeconv/html/CodeConventions.doc2.html#1852

The following table describes the parts of a class or interface declaration, in the order that they should appear

  1. Class/interface documentation comment (/*.../)
  2. class or interface statement
  3. Class/interface implementation comment (/.../), if necessary
  4. Class (static) variables
  5. Instance variables
  6. Constructors
  7. Methods


Most of the code I saw declared fields first, then methods (which is also suggested by the Java code conventions guide: http://www.oracle.com/technetwork/java/codeconventions-141855.html#1852)


Standard Java code conventions from Sun: http://java.sun.com/docs/codeconv/CodeConventions.pdf And Oracle: http://www.oracle.com/technetwork/java/codeconvtoc-136057.html


Fields before methods is the most common style.


I've mostly seen them at the top. One engineer I respect puts them at the bottom (to emphasize that you shouldnt be thinking about them :). You can avoid the Thinking About problem entirely by coding to interface, not classes. Also, take your vitamins. And floss!


From most code I've seen, fields get declared before methods. This isn't set in stone, as some people follow the common C++ practice of putting public fields and methods first, and then private fields and methods. I wouldn't treat it as a strict guideline; just ask yourself what makes your code more understandable by another person.


According to Sun's "Code Conventions for the Java Programming language", this is indeed the case: static fields first, then instance fields, then constructors, then methods.

However this part of the conventions is not quite as widely confirmed to as others: while using non-capitalized class names or capitalized variable names will immediately yield protests from the vast majority of Java programmers, many will accept putting fields next to the methods that operate on them.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜