其实,在往下读代码时,你会发现你的目光总停留于空白行之后的那一行。用空白行隔开每个命名空间、类、函数,代码的可读性会大大提升。
5 让紧密相关的代码相互靠近
如果说空白行隔开了概念,那么靠近的代码行则暗示了他们之间的紧密联系。所以,紧密相关的代码应该相互靠近。
举个反例(代码段1):
[csharp] view plain copy print?在CODE上查看代码片派生到我的代码片
public class ReporterConfig
{
/**
* The class name of the reporter listener
*/
private String m_className;
/**
- The properties of the reporter listener
*/
private List m_properties = new ArrayList();
public void addProperty(Property property)
{
m_properties.add(property);
}
}
再看个正面示例(代码段2):
[cpp] view plain copy print?在CODE上查看代码片派生到我的代码片
public class ReporterConfig
{
private String m_className;
private List m_properties = new ArrayList();
public void addProperty(Property property)
{
m_properties.add(property);
}
}
以上这段正面示例(代码段2)比反例(代码段1)中的代码好太多,它正好一览无遗,一眼就能看这个是有两个变量和一个方法的类。而再看看反例,注释简直画蛇添足,隔断了两个实体变量间的联系,我们不得不移动头部和眼球,才能获得相同的理解度。
6 基于关联的代码分布
关系密切的概念应该相互靠近。对于那些关系密切、放置于同一源文件中的概念,他们之间的区隔应该成为对相互的易懂度有多重要的衡量标准。应该避免迫使读者在源文件和类中跳来跳去。变量的声明应尽可能靠近其使用位置。
对于大多数短函数,函数中的本地变量应当在函数的顶部出现。例如如下代码中的is变量的声明:
[cpp] view plain copy print?在CODE上查看代码片派生到我的代码片
private static void readPreferences()
{
InputStream is= null;
try
{
is= new FileInputStream(getPreferencesFile());
setPreferences(new Properties(getPreferences()));
getPreferences().load(is);
}
catch (IOException e)
{
DoSomeThing();
}
}
而循环中的控制变量应该总在循环语句中声明,例如如下代码中each变量的声明:
[cpp] view plain copy print?在CODE上查看代码片派生到我的代码片
public int countTestCases()
{
int count = 0;
for (Test each : tests)
count += each.countTestCases();
return count;
}
在某些较长的函数中,变量也可能在某代码块的顶部,或在循环之前声明。例如如下代码中tr变量的声明:
[cpp] view plain copy print?在CODE上查看代码片派生到我的代码片
…
for (XmlTest test : m_suite.getTests())
{
TestRunner tr = m_runnerFactory.newTestRunner(this, test);
tr.addListener(m_textReporter);
m_testRunners.add(tr);
invoker = tr.getInvoker();
for (ITestNGMethod m : tr.getBeforeSuiteMethods())
{
beforeSuiteMethods.put(m.getMethod(), m);
}
for (ITestNGMethod m : tr.getAfterSuiteMethods())
{
afterSuiteMethods.put(m.getMethod(), m);
}
}
…
另外,实体变量应当在类的顶部声明(也有一些流派喜欢将实体变量放到类的底部)。
若某个函数调用了另一个,就应该把它们放到一起,而且调用者应该尽量放到被调用者上面。这样,程序就有自然的顺序。若坚定地遵守这条约定,读者将能够确信函数声明总会在其调用后很快出现。
概念相关的代码应该放到一起。相关性越强,则彼此之间的距离就该越短。
这一节的要点整理一下,大致就是:
变量的声明应尽可能靠近其使用位置。
循环中的控制变量应该在循环语句中声明。
短函数中的本地变量应当在函数的顶部声明。
而对于某些长函数,变量也可以在某代码块的顶部,或在循环之前声明。
实体变量应当在类的顶部声明。
若某个函数调用了另一个,就应该把它们放到一起,而且调用者应该尽量放到被调用者上面。
概念相关的代码应该放到一起。相关性越强,则彼此之间的距离就该越短。
7 团队遵从同一套代码规范
一个好的团队应当约定与遵从一套代码规范,并且每个成员都应当采用此风格。我们希望一个项目中的代码拥有相似甚至相同的风格,像默契无间的团队所完成的艺术品,而不是像一大票意见相左的个人所堆砌起来的残次品。
定制一套编码与格式风格不需要太多时间,但对整个团队代码风格统一性的提升,却是立竿见影的。
记住,好的软件系统是由一系列风格一致的代码文件组成的。尽量不要用各种不同的风格来构成一个项目的各个部分,这样会增加项目本身的复杂度与混乱程度。
四、范例代码
和上篇文章一样,有必要贴出一段书中推崇的整洁代码作为本次代码书写格式的范例。书中的这段代码采用java语言,但丝毫不影响使用C++和C#的朋友们阅读。
[cpp] view plain copy print?在CODE上查看代码片派生到我的代码片
public class CodeAnalyzer implements JavaFileAnalysis
{
private int lineCount;
private int maxLineWidth;
private int widestLineNumber;
private LineWidthHistogram lineWidthHistogram;
private int totalChars;
public CodeAnalyzer()
{
lineWidthHistogram = new LineWidthHistogram();
}
public static List findJavaFiles(File parentDirectory)
{
List files = new ArrayList();
findJavaFiles(parentDirectory, files);
return files;
}
private static void findJavaFiles(File parentDirectory, List files)
{
for (File file : parentDirectory.listFiles())
{
if (file.getName().endsWith(“.java”))
files.add(file);
else if (file.isDirectory())
findJavaFiles(file, files);
}
}
public void analyzeFile(File javaFile) throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(javaFile));
String line;
while ((line = br.readLine()) != null)
measureLine(line);
}
private void measureLine(String line)
{
lineCount++;
int lineSize = line.length();
totalChars += lineSize;
lineWidthHistogram.addLine(lineSize, lineCount);
recordWidestLine(lineSize);
}
private void recordWidestLine(int lineSize)
{
if (lineSize > maxLineWidth)
{
maxLineWidth = lineSize;
widestLineNumber = lineCount;
}
}
public int getLineCount()
{
return lineCount;
}
public int getMaxLineWidth()
{
return maxLineWidth;
}
public int getWidestLineNumber()
{
return widestLineNumber;
}
public LineWidthHistogram getLineWidthHistogram()
{
return lineWidthHistogram;
}
public double getMeanLineWidth()
{
return (double)totalChars / lineCount;
}
public int getMedianLineWidth()
{
Integer[] sortedWidths = getSortedWidths();
int cumulativeLineCount = 0;
for (int width : sortedWidths)
{
cumulativeLineCount += lineCountForWidth(width);
if (cumulativeLineCount > lineCount / 2)
return width;
}
throw new Error(“Cannot get here”);
}
private int lineCountForWidth(int width)
{
return lineWidthHistogram.getLinesforWidth(width).size();
}
private Integer[] getSortedWidths()
{
Set widths = lineWidthHistogram.getWidths();
Integer[] sortedWidths = (widths.toArray(new Integer[0]));
Arrays.sort(sortedWidths);
return sortedWidths;
}
}
五、小结:让代码不仅仅是能工作
代码的格式关乎沟通,而沟通是专业开发者的头等大事,所以良好代码的格式至关重要。