programming 发表于 2013-1-27 05:12:50

Java 编码规范

1 命名包,类,接口,方法以及变量时,尽量使用贴近问题域的表意丰富的名
   称。
   2包名应该用小写字母,不要出现下划线等符号,名词用有意义的缩写或
   者英文单词。

3 修改源代码时,应尽量保持与所修改系统的编码风格保持一致。
4所 有 包 名 使 用 必 须 使 用 com. 前 缀 , 所 有 项 目 使 用 com.
   .projects., company 是 公 司 简 称 ,
   project name 是项目的缩写。
第3章 格式规范
5get 和 set 方法,要注释,那是一定要的,因为别人调用的时候只看方法,不会看你的POJO对象属性,就是为什么要有SET GET 注释,如果你是一个开发多年的人一定会说要注释的,但也有不同的人会说太简单了不需要注释,那你说说为什么不要注释呢,别人调用方法的时候,还要跑过去看一下你的属性注释,。。。。
6) 只倒入明确需要的类,这样只要看导入列表,就可以知道该类依赖于哪些类
   和接口,保证可读性。

7) 类和接口中元素的布局顺序。
   1. 类和接口的文档描述
   2. 类和接口的声明
   3. 类的静态变量,按照 public,protected,package,private 的顺序。
   4. 实例变量,按照 public,protected,package,private 的顺序。
   5. 类的方法,无固定顺序。
8) 类的声明,基类和实现的接口应该独立成行,保证可读性。
   class UserManagerImpl
      extends AbstractManager
         implements IUserManager{
      ...
   }
9) 方法修饰关键字定义顺序。
   <public, protected, private > static abstract synchronized
   unuaual final native methodName
   注意访问标示符一定要在最前面。
   public static double square(double a);
   //避免: static public double square(double a);
      变量声明,采用 Camel 表示法不要在一行声明多个变量。
10)
   //推荐
   int level;
   int size;
   //避免
   int level, size;
      保证明确的类型转换,不要默认进行隐式类型转换
11)
   intValue = (int) floadValue; //避免 intValue = floatValue
      数组指示符紧跟类型变量
12)
   int[] a = new int; // 避免: int a[] = new int
   一个变量要代表独立的意思,不要在其生命周期赋予它不同的概念。
   int tempValue;
   tempValue = maxValue;
   ...
   ...
   tempValue = minValue;
   ...
   tempValue = anotherValue;
   tempValue 在生命周期内表示了各种各样的意图,增加理解代码的难度。
   应该为每个独立概念定义单独的变量:
   int tempMaxValue;
   int tempMinValue;
   int tempAnotherValue;
      仅仅循环控制变量才能出现在 for()循环中
13)
   sum = 0;
   for (i = 0; i < 100; i++) {
      sum += value;
   }
   //避免:
   for (i = 0, sum = 0; i < 100; i++){
      sum += value;
   }
      循环变量应靠近循环体初始化
14)
   isDone = false
   while(!isDone){
      ...
   }
   //避免
   isDone = false;
   ...
   ...
   while(!isDone){
      ...
   }
       避免长的布尔表达式,应换成多个更容易理解的表达式。
15)
   bool isFinished = (elementNo < 0) || (elementNo > maxElement);
   bool isRepeatedEntry = elementNo == lastElement;
   if (isFinished || isRepeatedEntry) {
       ...
   }
   // 避免
   if ((elementNo < 0) || (elementNo > maxElement)|| elementNo ==
lastElement) {
       ...
    }
       不要在条件语句中执行方法,以提高可读性
16)
   InputStream stream = File.open(fileName, "w");
   if (stream != null) {
       ...
   }
   //避免
   if (File.open(fileName, "w") != null)) {
       ...
   }
       代码缩进,应该使用 4 个空格为一个单位进行缩进。
17)
   public String invoke() throws Exception {
   ....String profileKey = "invoke: ";
         try {
         ....UtilTimerStack.push(profileKey);
             if (executed) {
             ....test = true;
         }
       catch{
       }
   }
      条件语句的主要形式,即使单条语句,也要使用括号括起来。
18)
   if (condition) {
      statements;
   }
   if (condition) {
      statements;
   } else {
      statements;
   }
   if (condition) {
      statements;
   } else if (condition) {
      statements;
   } else {
      statements;
   }
      空循环体也要使用完整的{}块
19)
   for (initialization; condition; update) {
      ;
   }
      switch 语句的使用格式
20)
   switch (condition) {
      case ABC :
         statements;
         //穿透,一定要做出注释
      case DEF :
         statements;
         break;
      case XYZ :
         statements;
         break;
      default :
         statements;
         break;
   }
      try-catch 使用格式
21)
   try {
      statements;
   }
   catch (Exception exception) {
      statements;
   }
   try {
      statements;
   }
   catch (Exception exception) {
      statements;
   }
   finally {
      statements;
   }
      空格的使用
22)
    1. 运算符两边应该各有一个空格。
    2. Java 保留字后面应跟随一个空格。
    3. 逗号后面应跟随一个空格。
    4. 冒号两个应各有一个空格。
    5. 分号后面应跟随一个空格。
   a = (b + c) * d;          // NOT: a=(b+c)*d
   while (true) {            // NOT: while(true){ ...
   doSomething(a, b, c, d);// NOT: doSomething(a,b,c,d);
   case 100 :                // NOT: case 100:
   for (i = 0; i < 10; i++) { // NOT: for(i=0;i<10;i++){ ...
      空行的使用
23)
   1. 文件头部注释、package 语句和 import 语句之间。
   2. class 之间
   3. 方法之间
   4. 方法中,变量的申明和具体代码之间。
   5. 逻辑上相关的语句段之间
   6. 块注释和行注释的前面
   ▽ --- 代表空行
   /**
*
*/

package XXX.XXX;

import XXX.XXX.XXX.XXX;

/**
*
*/
public class UserFileAccess {

    //
    private int myObjId;

    /**
   *
   */
    public UserFileAccess() {
      ・・・
    }

    /**
   *
   */
    public void getCtlInfo() {
      int   count;
      String msg;

      count = 100;
      ・・・

      //实现代码注释前空行
      msg = “MESSAGE”;

      count = dataCount;
      if (count == 0) {
            ・・・
      }
    }

/**
*
    */
   private class UserFileRead {
       逻辑上紧密相关的代码块应该用一个空行分开。
24)
   // Create a new identity matrix
   Matrix4x4 matrix = new Matrix4x4();
   // Precompute angles for efficiency
   double cosAngle = Math.cos(angle);
   double sinAngle = Math.sin(angle);
   //   Specify   matrix as   arotation transformation
   matrix.setElement(1, 1, cosAngle);
   matrix.setElement(1, 2, sinAngle);
   matrix.setElement(2, 1, -sinAngle);
   matrix.setElement(2, 2, cosAngle);
   // Apply rotation
   transformation.multiply(matrix);
       为了保证可读性,变量名应该左对齐。
25)
   TextFile file;
   int       nPoints;
   double    x, y;
   //避免
   TextFile file;
   int nPoints;
   double x, y;
       像前面一般规则里说的那样,         任何提高代码可读性的排版都可以去尝试,
26)
   下面是一些例子。
   if      (a == lowValue)      compueSomething();
   else if   (a == mediumValue) computeSomethingElse();
   else if   (a == highValue)   computeSomethingElseYet();
   value =   (potential         * oilDensity)   / constant1 +
             (depth             * waterDensity) / constant2 +
             (zCoordinateValue * gasDensity)    / constant3;
   minPosition =         computeDistance(min,      x, y, z);
   averagePosition =   computeDistance(average, x, y, z);
   switch (phase) {
       case PHASE_OIL   :   text= "Oil";    break;
       case PHASE_WATER :   text= "Water"; break;
       case PHASE_GAS    :text= "Gas";    break;
   }
       当对 if 语句中的条件进行折行时,应该使折行的条件语句相对主功能
27)
   语句再行缩进 4 个空格,以突出主要功能语句。
    //使用这种缩进,突出主要功能语句。
    if ((condition1 && condition2)
         || (condition3 && condition4)
         ||!(condition5 && condition6)) {
       doSomethingAboutIt();
   }
    //避免使用这种缩进,主功能语句不突出。
    if ((condition1 && condition2)
       || (condition3 && condition4)
       ||!(condition5 && condition6)) {
       doSomethingAboutIt();
    }
       三元条件运算符
28)
   可以使用如下三种表达方式,条件要用括号括起来。
    alpha = (aLongBooleanExpression) ? beta : gamma;
    alpha = (aLongBooleanExpression) ? beta
                                    : gamma;
    alpha =   (aLongBooleanExpression)
            ? beta
            : gamma
页: [1]
查看完整版本: Java 编码规范