代码规范

今天看了《代码整洁之道》一书,做笔记如下:

 

1.名副其实、见名知意

 1 public List<int[]> getThem() {
 2 
 3         List<int[]> list1 = new ArrayList<int[]>();
 4 
 5         for (int[] x : theList) {
 6             if (x[0] == 4) {
 7                 list1.add(x);
 8             }
 9         }
10 
11         return list1;
12     }

看此方法,方法、变量定义的让人蛋疼,不是你自己写的你根本不知道这段代码是干什么的,就算是你自己写的你恐怕也不一定知道!

下面优化一下:

 1 public List<int[]> getFlaggedCells() {
 2 
 3         List<int[]> flaggedCell = new ArrayList<int[]>();
 4 
 5         for (int[] cell : gameBoard) {
 6             if (cell[STATUS_VALUE]==FLAGGED) {
 7                 flaggedCell.add(cell);
 8             }
 9         }
10 
11         return flaggedCell;
12     }

看看现在就好多了吧,变量和方法名起的有声有色,估计能看懂英文的就该知道这个方法里面的意思了,一目了然都不用加注释了。

现在已经比原来直观多了,but...不急,咱接着优化:

 1 public List<Cell> getFlaggedCells() {
 2 
 3         List<Cell> flaggedCell = new ArrayList<int[]>();
 4 
 5         for (Cell cell : gameBoard) {
 6             if (cell.isFlagged()) {
 7                 flaggedCell.add(cell);
 8             }
 9         }
10 
11         return flaggedCell;
12     }

看看现在, 新建一个Cell类,把cell[STATUS_VALUE]==FLAGGED写成它的方法isFlagged(),现在才是真正的一目了然啊,亲!

 

未完待续...

posted @ 2013-04-18 15:58  老笨孩  阅读(247)  评论(0编辑  收藏  举报