侧边栏壁纸
博主头像
疯狂IT人博主等级

疯狂编程博客,分享IT编程的技术博客,用程序员视角总结分享IT编程和互联网知识的那些事儿。

  • 累计撰写 189 篇文章
  • 累计创建 20 个标签
  • 累计收到 3 条评论

目 录CONTENT

文章目录

代码整洁之道

疯狂IT人
2022-11-06 / 0 评论 / 0 点赞 / 418 阅读 / 605 字 / 正在检测是否收录...

有意义的命名

名副其实

比如变量、函数、类的名称要能表示它是用来做什么事情的,应该怎么使用,不需要通过额外的注释,就能说明它的作用。
比如下面这段代码,乍一看根本不知道是用来做什么的:

public List<int[]> getThem() {
    List<int[]> list1 = new ArrayList<int[]>();
    for (int[] x : theList)
        if (x[0] == 4)
            list1.add(x);
    return list1;
}

我们需要通过上下文分析,才能知道这段代码是干什么的。如果我们对变量和函数赋予有意义的名称时,就能清晰的知道这段代码的作用,另外对 for、if 等代码块,建议使用大括号包起来,这样既对代码阅读有好处,又能避免不必要的错误。

public List<int[]> getFlaggedCells() {
    List<int[]> flaggedCells = new ArrayList<int[]>();
    for (int[] cell : gameBoard) {
        if (cell[STATUS_VALUE] == FLAGGED) {
            flaggedCells.add(cell);
        }
    }
    return flaggedCells;
}

做有意义的区分

为满足编译器或解释器的需要而做区分。例如,在同一作用域内两个变量是不能重名,我们经常使用 a1,a2 这种方式来避免编译出错。但是这种命名方式没有提供正确信息。比如下面这段代码:

public static void copyChars(char a1[], char a2[]) {
    for (int i = 0; i < a1.length; i++) {
        a2[i] = a1[i];
    }
}

a1 和 a2 不能表示对应变量的实质意义,参数名改为 source 和 destination 会像样许多:

public static void copyChars(char souce[], char destination[]) {
    for (int i = 0; i < souce.length; i++) {
        destination[i] = souce[i];
    }
}

废话是另一种没意义的区分。比如 Product 类和 ProductInfo 或 ProductData 类,它们的名称虽然不同,但是意义却是一样的。Info 和 Data 就像 a、an 和 the 一样,是意义含混的废话。

使用读的出来的名称

变量、函数、类的名称尽量使用能够读的出来的名称。比如下面的代码,在没有注释的情况下,根本不知道这些属性代表什么:

class DtaRcrd102 {
    private Date genymdhms;
	private Date modymdhms;
	private final String pszqint = "102";
	/* ... */
}

改成可读的名称:generationTimestamp 表示生成时间戳

class Customer {
    private Date generationTimestamp;
	private Date modificationTimestamp;
	private final String recordId = "102";
	/* ... */
}

参考

《代码整洁之道》

0

评论区