---
title: "《Clean Code》总结 有意义的命名"
author: "mshijie"
date: "2010-03-12T11:57:19Z"
tags: ["IDE", "J#", "Qt"]
categories: ["编程语言"]
slug: "clean-code"
draft: false
lastmod: "2010-03-12T18:18:18Z"
id: 613982
url: "https://mshijie.iteye.com/blog/613982"
---

编写代码时，尽量使用有意义的名称命名类、方法、变量等

## 1.使用能揭示意图的名称

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

 改变为，就能更能说明名称的意图

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

 又例如

```
int elapsedTimeInDays;
int d; // elapsed time in days
```

 前者使用的表明意图的名称比注释更清晰

 

## 2.避免误导

例如使用accountList时，要小心，这向阅读者传达的信息是，这是一个List，但如果不是列表，而只是一个数组。简单的使用accounts或者accountGroup比较安全

## 3.使用有意义的区分

在一段代码中清除存在相同类型的两个不同变量  
public static void copyChars(char a1\[], char a2\[]) {}  
public static void copyChars(char source\[], char destination\[]) {}  
后者的区分更有意义  
又例如类名Product，ProductInfo，ProductData三个类在区分上很不明确，不能直接看出三个类的区别  
getActiveAccount();  
getActiveAccounts();  
getActiveAccountInfo();  
这个三个方法名也会给使用者带来麻烦

 

## 4.使用可发音的命名

一个经典的例子就是genymdhms(generation date, year, month, day, hour, minute, and second)，这个方法无法发音，就不方便和他人交流。generateTimeStamp是个更好的名字。  
例如

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

 重构为

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

 

## 5.使用能搜索的名称

```
for (int j=0; j<34; j++) {
    s += (t[j]*4)/5;
}
```

 其中的产量数字，不能有效搜索到，不方便修改。

```
int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j=0; j < NUMBER_OF_TASKS; j++) {
    int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
    int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);
    sum += realTaskWeeks;
}
```

 这段更长的代码更方便搜索和修改 

## 6.避免在名称中编码附加信息

例如，匈牙利命名法，m\_或\_前缀，IShapeFactory接口前缀I，现在的IDE已经可以更有效的完成前三种的功能，已经没有这样使用的必要了。

 

## 7.类名使用名词单数形式Customer, WikiPage, Account

 

## 8.方法名使用动词或动词短语postPayment, deletePage, save

 

## 9.同一个单词使用同一种命名

例如fetch，retrieve，get三者表示同一个意思，最好统一使用一个

 

## 10.使用程序编写领域的名词

例如AccountVisitor，JobQueue，UserFacade

 

## 11.使用问题领域的名词

 

## 12.添加有意义的上下文

 

```
private void printGuessStatistics(char candidate, int count) {
 String number;
 String verb;
 String pluralModifier;
 if (count == 0) {
  number = "no";
  verb = "are";
  pluralModifier = "s";
 } else if (count == 1) {
  number = "1";
  verb = "is";
  pluralModifier = "";
 } else {
  number = Integer.toString(count);
  verb = "are";
  pluralModifier = "s";
 }
 String guessMessage = String.format(
  "There %s %s %s%s", verb, number, candidate, pluralModifier
 );
 print(guessMessage);
}
```

 重构为

```
public class GuessStatisticsMessage {
 private String number;
 private String verb;
 private String pluralModifier;
 
 public String make(char candidate, int count) {
  createPluralDependentMessageParts(count);
  return String.format(
   "There %s %s %s%s",
   verb, number, candidate, pluralModifier );
 }
 
 private void createPluralDependentMessageParts(int count) {
  if (count == 0) {
   thereAreNoLetters();
  } else if (count == 1) {
   thereIsOneLetter();
  } else {
   thereAreManyLetters(count);
  }
 }
 
 private void thereAreManyLetters(int count) {
  number = Integer.toString(count);
  verb = "are";
  pluralModifier = "s";
 }
 private void thereIsOneLetter() {
  number = "1";
  verb = "is";
  pluralModifier = "";
 }
 private void thereAreNoLetters() {
  number = "no";
  verb = "are";
  pluralModifier = "s";
 }
}
```

 就能给number，verb和pluralModifier提供一个很清晰的上下文

 

## 13.不要添加没有必要的上下文

例如一个应用程序交Gas Station Deluxe，没有必要在所有东西前面添加GSD。QT的所有类前加Q就是没有必要的。