Good Java Style: Part 2

Good Java Style: Part 2
By Thornton Rose

Introduction
This is the conclusion of a two-part series on Java coding style. In Good Java Style: Part 1

, I introduced my case for writing Java code using good habits, explained why we should care about the way our code looks, and illustrated some general elements of good Java style. In this part, I illustrate more elements of good style and bring my case to a conclusion.

Source Files
There are many ways that a Java source file can be organized. Here is one that works well:

File header comment (optional).
Package declaration.
Blank line or other separator.
Import statements.
Blank line or other separator.
Class(es).

Example 1. Bad File Organization.

   package org.rotpad;
   import java.awt.*;
   import javax.swing.event.*;
   import org.javacogs.*;
   import javax.swing.*;
   import java.awt.event.*;
   class Foo {
    ...
   }
   public class RotPad extends JFrame {
    ...
   }

Example 2. Good File Organization.

   package org.rotpad;
   
   // Java classes
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.event.*;
   
   // JavaCogs classes
   import org.javacogs.*;
   
   /**
    * RotPad is a simple GUI application for performing rotation ciphers on plain
    * text.
    *
    * @author Thornton Rose
    * @version 1.0
    */
   public class RotPad extends JFrame {
      ...
   }
   
   //-----------------------------------------------------------------------------
   
   /**
    * Foo is ...
    *
    * @author Thornton Rose
    * @version 1.0
    */
   class Foo {
      ...
   }

Import Statements
A complex class can have a large number of imports, which can get unruly, especially if you prefer to import individual classes instead of whole packages (e.g., java.awt.*). To get a handle on imports, organize them as follows:

Java standard classes (java.*).
Java extension classes (javax.*).
Third-party classes.
Application classes.

Be sure to comment the third-party and application classes, particularly those that do not have obvious names. Use end-of-line comments, or put a comment at the beginning of the section. Also, if you really want to be a perfectionist, order each group of imports alphabetically.

Example 3. Bad Import Style.

   import java.util.*;
   import javax.swing.*;
   import java.awt.event*;
   import com.gensym.com.*;
   import javax.swing.table.*;
   import com.pv.jfcx.*;
   import java.awt.*;
   import com.melthorn.util.*;

Example 4a. Good Import Style.

   import java.awt.*;
   import java.awt.event*;
   import java.util.*;
   import javax.swing.table.*;
   import com.gensym.com.*;     // BeanXporter
   import com.pv.jfcx.*;        // ProtoView
   import com.melthorn.util.*;  // Utilities

Example 4b. Good Import Style.

   
   // Java classes
   import java.awt.*;
   import java.awt.event*;
   import java.util.*;
   import javax.swing.table.*;
                           
   // BeanXporter
   import com.gensym.com.*;     
                           
   // ProtoView GUI components
   import com.pv.jfcx.*;
                           
   // Application classes
   import com.melthorn.util.*;

Classes
Organizing a Java source file without organizing the classes in it would not gain you much in the way of proper style. Here's how to organize the classes in your source files:

Javadoc comment or other header comment.
Class declaration.
Field declarations.
Blank line or other separator.
Constructors.
Blank line or other separator.
Methods, except main()

, grouped logically.
Blank line or other separator.
Inner classes.
Blank line or other separator.
main()

.

Example 5. Bad Class Style.

   // RotPad -- GUI app. for ROT ciphering
   public class RotPad extends JFrame {
   private static final String TRANSFORM_ROT13    = "ROT13";
   private static final String TRANSFORM_ROT13N5  = "ROT13N5";
   private static final String TRANSFORM_ROTASCII = "ROT-ASCII";
   
   private void jbInit() throws Exception {
      ...
   }
   
   public static final String TITLE   = "RotPad";
   public static final String VERSION = "1.0";
   
   public static void main(String[] args) {
      ...
   }
   
   public RotPad() {
      ...
   }
   
   private JPanel jPanel1 = new JPanel();
   private JPanel jPanel2 = new JPanel();
   private BorderLayout borderLayout1 = new BorderLayout();
   ...
   }

Example 6. Good Class Style.

   /**
    * RotPad is a simple GUI application for performing rotation ciphers on plain
    * text.
    *
    * @author Thornton Rose
    * @version 1.0
    */
   public class RotPad extends JFrame {
      // Public constants
       
      public static final String TITLE   = "RotPad";
      public static final String VERSION = "1.0";
       
      // Private constants
      
      private static final String TRANSFORM_ROT13    = "ROT13";
      private static final String TRANSFORM_ROT13N5  = "ROT13N5";
      private static final String TRANSFORM_ROTASCII = "ROT-ASCII";
     
      // GUI components [JBuilder generated]
       
      private BorderLayout borderLayout1 = new BorderLayout();
      private JPanel jPanel1 = new JPanel();
      private JPanel jPanel2 = new JPanel();
      ...
      
      /**
       * Construct a new instance of this class.
       */
      public RotPad() {
         ...
      }
      
      /**
       * Initialize UI components. [JBuilder generated]
       */
      private void jbInit() throws Exception {
         ...
      }
       
      ...
      
      //--------------------------------------------------------------------------
     
      /**
       * Start the application.
       */
      public static void main(String[] args) {
         ...
      }
   }

Field Declarations
Some classes have a large number of fields, which can become difficult to maintain if they are not organized well. Organize them as follows:

Public contstants (final and static final).
Public variables.
Protected constants.
Protected variables.
Package constants.
Package variables.
Private constants.
Private variables.

Additionally, use the following guidelines for writing field declarations:

Use one declaration per line.
Use Javadoc comments on public and protected fields, at minimum.
Use UPPERCASE for the names of constants. Using uppercase makes them much more obvious in both declarations and expressions.
If you use a tool that generates field declarations, such as JBuilder or Visual Cafe, keep the generated fields separate from the other fields. It makes maintenance of the UI code much easier.

Example 7. Bad Field Style.

   public class CustomerSearchDialog extends JDialog {
      private JLabel firstNameLabel = new JLabel();
      private JLabel lastNameLabel = new JLabel();
      public static final RESULT_SELECT = 1;
      private Vector results = new Vector(); // Search results.
      private DefaultTableModel tableModel = new DefaultTableModel();
      public static final RESULT_CANCEL = 0;
      // ...
   }

Example 8. Good Field Style.

   /**
    * ...
    */
   public class CustomerSearchDialog extends JDialog {
      /**
       * Indicates that search was cancelled; returned by showDialog() when
       * user clicks cancel button.
       */
      public static final RESULT_CANCEL = 0;
      
      /**
       * Indicates that a customer was selected; returned by showDialog() when
       * user clicks select button.
       */
      public static final RESULT_SELECT = 1;
      
      private Vector            results    = new Vector();             // Search results.
      private DefaultTableModel tableModel = new DefaultTableModel();  // Grid model.
      
      // GUI fields. [JBuilder]
      
      private JLabel firstNameLabel = new JLabel();
      private JLabel lastNameLabel = new JLabel();
      // ...
   }

Method Declarations
Use the following guidelines for writing method declarations:

Always have a Javadoc comment or some other header comment.
Always put the access modifier first.
If the line is too long, break it into one or more lines.
If the method has more than a few parameters, consider putting each on a separate line.
Don't put whitespace between the method name and the opening parenthesis ("(").
Always put whitespace (which could be a line break) between the closing parenthesis (")") and the opening brace ("{").

Example 9. Bad Method Style.

   public int getTypeCount (String custType)
   {
   ...
   }
   static public getInstance(){ ... };
   public void showRange()
      throws RangeException {
    ...
   }

Example 10. Good Method Styles.

   /**
    * Return the single instance of this class.
    */
   public static CalculationEngine getInstance() {
      return instance;
   }
   
   /**
    * Calculate the consumption coefficient.
    */
   public float calculateConsumptionCoefficient(int base, float variance,
         int iterations) throws RangeException {
      // ...
   }
  
   /**
    * Calculate the consumption coefficient.
    */
   public float calculateConsumptionCoefficient(
         int base,
         float variance,
         int iterations)
      throws RangeException
   {
      // ...
   }
   
   /**
    * Calculate the consumption coefficient.
    */
   public float calculateConsumptionCoefficient(int base,
                                                float variance,
                                                int iterations)
      throws RangeException
   {
      // ...
   }

Conclusion
In conclusion, I have one final thought for you on the subject of code style. No matter what guidelines you follow, and no matter how fervent your beliefs about things like indent style (cf., Raymond, "Indent Style"), remember that when you write code your overall goal should be to make the code understandable and maintainable by someone else.

Related Links

Indent Style, The Jargon File, Eric S. Raymond.
Tabs vs. Spaces, Jamie Zawinski.
Writing Robust Java Code — The Ambysoft Inc. Coding Standards for Java, Scott Ambler.
Draft Java Coding Standard, Doug Lea.
Java Code Conventions, Sun Microsystems, Inc.
How to Write Doc Comments for Javadoc, Sun Microsystems, Inc.
The Jargon File (known in print as The New Hacker's Dictionary), Eric S. Raymond.

About the Author
Thornton Rose is a contract software developer in Atlanta, Ga. He can be reached via e-mail at thornton.rose@mindspring.com.

时间: 2024-05-22 06:24:11

Good Java Style: Part 2的相关文章

Good Java Style: Part 1

Good Java Style: Part 1By Thornton Rose IntroductionHaving worked as a software developer and consultant for many years, I have seen a large amount of code in a variety of programming languages. It has run the gamut from elegant to ugly, and unfortun

优秀Java程序员的编程风格

今天突发奇想,对编码习惯和编程风格很感兴趣,于是乎,找了一下关于编程风格(Java篇)的资料,希望对爱好编码或者开始学习编码的同学有帮助! 来自<The Elements of Java Style>-<Java编程风格>一书,值得一读的书籍,会让你在细节上节省很多时间,合作之间更加愉快! 好处不多说了,但是有几个原则如下: 1.保持原有风格 2.坚持最小惊奇原则 3.第一次就做对 4.记录所有非规范行为 格式规范: 1.缩进嵌套的代码:在每个代码块和嵌套中加入缩进,缩进代码,加强

敏捷开发中高质量Java代码开发实践

概述 Java 项目开发过程中,由于开发人员的经验.代码风格各不相同,以及缺乏 统一的标准和管理流程,往往导致整个项目的代码质量较差,难于维护,需要较 大的测试投入和周期等问题.这些问题在一个项目组初建.需求和设计均具有不 完全可预期性和完备性的全新项目中将尤为突出.本文将结合敏捷开发周期短, 变化快等特点,介绍如何通过在开发过程中采取一系列步骤来保证和提高整个开 发团队的代码质量,并阐述了每一步可以利用的工具和最佳实践,从而使开发过 程更加规范化,成就高质量的代码,减少测试的投入,并促进整个团

Github优秀java项目集合(中文版) - 涉及java所有的知识体系 -- good

Java资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列的资源整理.awesome-java 就是 akullpp 发起维护的 Java 资源列表,内容包括:构建工具.数据库.框架.模板.安全.代码分析.日志.第三方库.书籍.Java 站点等等.伯乐在线已经把 awesome-java 资源列表翻成中文后发布于 ImportNew. Awesome 系列虽然挺全,但基本只对收录的资源做了极为简要的介绍,如果有更详细的中文介绍,对相应开发者的帮助会更

Java资源大全中文版(Awesome最新版)

目录 业务流程管理套件 字节码操作 集群管理 代码分析 编译器生成工具 构建工具 外部配置工具 约束满足问题求解程序 持续集成 CSV解析 数据库 数据结构 时间日期工具库 依赖注入 开发流程增强工具 分布式应用 分布式数据库 发布 文档处理工具 函数式编程 游戏开发 GUI 高性能计算 IDE 图像处理 JSON JVM与JDK 基于JVM的语言 日志 机器学习 消息传递 杂项 应用监控工具 原生开发库 自然语言处理 网络 ORM PDF 性能分析 响应式开发库 REST框架 科学计算与分析

[码]国外大牛整理的Java资源 !

先码为敬. Java几乎是许多程序员们的入门语言,并且也是世界上非常流行的编程语言.国外程序员Andreas Kull在其Github上整理了非常优秀的Java开发资源,推荐给大家. [编者按]Java几乎是许多程序员们的入门语言,并且也是世界上非常流行的编程语言.国外程序员Andreas Kull在其Github上整理了非常优秀的Java开发资源,推荐给大家.译文由ImportNew- 唐尤华翻译完成. 以下为具体资源列表. 构建 这里搜集了用来构建应用程序的工具. Apache Maven:

资料推荐--Google Java编码规范

之前已经推荐过Google的Java编码规范英文版了: http://google-styleguide.googlecode.com/svn/trunk/javaguide.html 虽然这篇文章的英文很简单,但是最近发现有人翻译了这篇文章,所以专门写一篇文章推荐一下: http://hawstein.com/posts/google-java-style.html   同时为了避免原始文章丢失,所以转了一下: 作者:Hawstein 出处:http://hawstein.com/posts/

Google Java编程风格指南

作者:Hawstein出处:http://hawstein.com/posts/google-java-style.html声明:本文采用以下协议进行授权: 自由转载-非商用-非衍生-保持署名|Creative Commons BY-NC-ND 3.0 ,转载请注明作者及出处. 目录 前言 源文件基础 源文件结构 格式 命名约定 编程实践 Javadoc 后记 前言 这份文档是Google Java编程风格规范的完整定义.当且仅当一个Java源文件符合此文档中的规则, 我们才认为它符合Googl

阿里巴巴Java开发手册评述

笔者作为一名有数年工作经验的Java程序员,仔细研读了这份手册,觉得其是一份不可多得的好材料.阿里巴巴在发布时所说,"阿里巴巴集团推出的<阿里巴巴Java开发手册(正式版)>是阿里巴巴近万名开发同学集体智慧的结晶,以开发视角为中心,详细列举如何开发更加高效.更加容错.更加有协作性,力求知其然,更知其不然,结合正反例,让Java开发者能够提升协作效率.提高代码质量." 同时,阿里巴巴也期望这套Java统一规范标准将有助于提高行业编码规范化水平,帮助行业人员提高开发质量和效率.