我们程序员就像一群代码猴子,上蹿下跳的,自以为理解了代码的真谛。抓住了一个桃子,实现了一个功能,就得意洋洋了,而无视自己造成的代码混乱,而且让它一直混乱下去。就这样一个自认为“可运行”的程序就在我们眼中慢慢的坏掉。
书本例子
public class CleanCodeDemo {
List<int[]> theList = Arrays.asList(new int[]{1, 2, 3, 4});
public List<int[]> getThem() {
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList)
if (x[0] == 4)
list1.add(x);
return list1;
}
/*************************优化后***********************************/
static int STATUS_VALUE = 0;
static int FLAGGERD = 4;
List<int[]> gameBoard = Arrays.asList(new int[]{1, 2, 3, 4});
public List<int[]> getFlaggedCells() {
List<int[]> flaggerCells = new ArrayList<int[]>();
for (int[] cell : gameBoard)
if (cell[STATUS_VALUE] == FLAGGERD)
flaggerCells.add(cell);
return flaggerCells;
}
/*************************再次优化***********************************/
class Cell {
int [] cell;
public boolean isFlagged(){
boolean is = false;
if (cell[STATUS_VALUE] == FLAGGERD)
is = true;
return is;
}
}
List<Cell> gameBoard2 = Arrays.asList(new Cell());
protected List<Cell> getFlaggedCells() {
List<Cell> flaggerCells = new ArrayList<Cell>();
for (Cell cell : gameBoard2)
if (cell.isFlagged())
flaggerCells.add(cell);
return flaggerCells;
}
粗读总结
- 类名和对象名应该时名词或者名称性短语;
- 方法名应该时动词或者动词短语;
- 函数应该做一件事。做好这件事。只做这件事。
- 确保函数只做一件事,函数中的语句都要在一个抽象层级上。
- 向下规则:每个函数后面都跟着位于下一抽象层级的函数,
- 简单的说程序就像一系列的文章段落每一段描述当前的抽象层级,并引用下一抽象层级的后
- 最理想的函数时零参数、其次为一;
- 一元函数分为void事件函数、转化类型函数 InputStream fileOpen(“myfile”)
- 尽可能将二元转化为一元;
- 减少使用三元函数的次数
- 超过三元考虑封装为类
完整例子