“Don’t comment bad code—rewrite it.”——Brian W.Kernighan and P.J.Plaugher

The proper use of comments is to compensate for our failure to express ourself in code.

Truth can only be found in one place: the code.

  • Comments Do Not Make Up for Bad Code

    Rather than spend your time writting the comments that explains the mess you have made, spend it cleaning that mess.

  • Explain Yourself in Code

    In many cases it's simply a matter of creating a function that says the same thing as the comment you want to write.

  • Good Comments

    The only truly good comment is the comment you found a way not to write.

    • Legal Comments

      // copyright (c) ...

    • Informative Comments

      // format matched kk:mm:ss EEE, MMM dd, yyyy
      Pattern timeMatcher = Pattern.compile(
      "\\d*:\\d*:\\d* \\w*, \\w* \\d*, \\d*");
    • Explanation of Intent

    • Clarification

      Translate the meaning of some obscure argument or return value into something that's readable.

    • Warning of Consequences

    • TODO Comments

    • Amplification

      Amplify the importance of something that may otherwise seem inconsequential.

    • Javadocs in Public APIs

  • Bad Comments

    • Mumbling

      Any comment that forces you to look in another module for the meaning of that comment has failed to communicate to you and is not worth the bits it consumes.

    • Redundant Comments

      Comments that take longer to read than the code itself.

    • Misleading Comments

    • Mandated Comments

      It is just plain silly to have a rule that says that every function must have a javadoc, or every varible must have a comment.

    • Journal Comments

      Remove the comment log of editing and have source code control system to do it.

    • Noise Comments

      • Restate the obvious
      • vent
    • Don't Use a Comment When You Can Use a Function or a Variable

    • Position Markers

      Avoid overuse of banners.

    • Closing Brace Comments

      If you find yourself wanting to mark your closing braces, try to shorten your functions instead.

    • Attributions and Bylines

      Use source code control system instead.

    • Commented-Out Code

      Just delete it and again use source code control system instead.

    • HTML Comments

      It should be the responsibility of the tools. (like Javadoc)

    • Nonlocal Information

      Make sure a comment describes the code it appears near.

    • Too Much Information

      Don't put interesting historical discussions or irrelevant descriptions of details into your comments.

    • Inobvious Connection

      It is a pity when a comment needs its own explanation.

    • Function Headers

      A well-chosen name for a small function that does one thing is usually better than a comment header.

    • Javadocs in Nonpublic Code

e.g.

Bad code:

// Clean Code
// Listing 4-7
// GeneratePrimes.java /**
* This class Generates prime numbers up to a user specified
* maximum. The algorithm used is the Sieve of Eratosthenes.
* <p>
* Eratosthenes of Cyrene, b. c. 276 BC, Cyrene, Libya --
* d. c. 194, Alexandria. The first man to calculate the
* circumference of the Earth. Also known for working on
* calendars with leap years and ran the library at Alexandria.
* <p>
* The algorithm is quite simple. Given an array of integers
* starting at 2. Cross out all multiples of 2. Find the next
* uncrossed integer, and cross out all of its multiples.
* Repeat untilyou have passed the square root of the maximum
* value.
*
* @author Alphonse
* @version 13 Feb 2002 atp
*/
import java.util.*; public class GeneratePrimes {
/**
* @param maxValue is the generation limit.
*/
public static int[] generatePrimes(int maxValue) {
if (maxValue >= 2) { // the only valid case
// declarations
int s = maxValue + 1; // size of array
boolean[] f = new boolean[s];
int i; // initialize array to true.
for (i = 0; i < s; i++)
f[i] = true; // get rid of known non-primes
f[0] = f[1] = false; // sieve
int j;
for (i = 2; i < Math.sqrt(s) + 1; i++) {
if (f[i]) { // if i is uncrossed, cross its multiples.
for (j = 2 * i; j < s; j += i)
f[j] = false; // multiple is not prime
}
} // how many primes are there?
int count = 0;
for (i = 0; i < s; i++) {
if (f[i])
count++; // bump count.
}
int[] primes = new int[count]; // move the primes into the result
for (i = 0, j = 0; i < s; i++) {
if (f[i]) // if prime
primes[j++] = i;
}
return primes; // return the primes
}
else // maxValue < 2
return new int[0]; // return null array if bad input.
}
}

Good code:

// Clean Code
// Listing 4-8
// PrimeGenerator.java (refactored) /**
* This class Generates prime numbers up to a user specified
* maximum. The algorithm used is the Sieve of Eratosthenes.
* Given an array of integers starting at 2:
* Find the first uncrossed integer, and cross out all its
* multiples. Repeat until there are no more multiples
* in the array.
*/
public class PrimeGenerator
{
private static boolean[] crossedOut;
private static int[] result; public static int[] generatePrimes(int maxValue)
{
if (maxValue < 2)
return new int[0];
else
{
uncrossIntegersUpTo(maxValue);
crossOutMultiples();
putUncrossedIntegersIntoResult();
return result;
}
} private static void uncrossIntegersUpTo(int maxValue)
{
crossedOut = new boolean[maxValue + 1];
for (int i = 2; i < crossedOut.length; i++)
crossedOut[i] = false;
} private static void crossOutMultiples()
{
int limit = determineIterationLimit();
for (int i = 2; i <= limit; i++)
if (notCrossed(i))
crossOutMultiplesOf(i);
} private static int determineIterationLimit()
{
// Every multiple in the array has a prime factor that
// is less than or equal to the root of the array size,
// so we don't have to cross out multiples of numbers
// larger than that root.
double iterationLimit = Math.sqrt(crossedOut.length);
return (int) iterationLimit;
} private static void crossOutMultiplesOf(int i)
{
for (int multiple = 2*i;
multiple < crossedOut.length;
multiple += i)
crossedOut[multiple] = true;
} private static boolean notCrossed(int i)
{
return crossedOut[i] == false;
} private static void putUncrossedIntegersIntoResult()
{
result = new int[numberOfUncrossedIntegers()];
for (int j = 0, i = 2; i < crossedOut.length; i++)
if (notCrossed(i))
result[j++] = i;
} private static int numberOfUncrossedIntegers()
{
int count = 0;
for (int i = 2; i < crossedOut.length; i++)
if (notCrossed(i))
count++;
return count;
}
}

Clean Code – Chapter 4: Comments的更多相关文章

  1. Clean Code–Chapter 7 Error Handling

    Error handling is important, but if it obscures logic, it's wrong. Use Exceptions Rather Than Return ...

  2. Clean Code – Chapter 3: Functions

    Small Blocks and Indenting The blocks within if statements, else statements, while statements, and s ...

  3. Clean Code – Chapter 2: Meaningful Names

    Use Intention-Revealing Names The name should tell you why it exists, what it does, and how it is us ...

  4. Clean Code – Chapter 6 Objects and Data Structures

    Data Abstraction Hiding implementation Data/Object Anti-Symmetry Objects hide their data behind abst ...

  5. Clean Code – Chapter 5 Formatting

    The Purpose of Formatting Code formatting is about communication, and communication is the professio ...

  6. “Clean Code” 读书笔记序

    最近开始研读 Robert C.Martin 的 “Clean Code”,为了巩固学习,会把每一章的笔记整理到博客中.而这篇博文作为一个索引和总结,会陆续加入各章的笔记链接,以及全部读完后的心得体会 ...

  7. [转]Clean Code Principles: Be a Better Programmer

    原文:https://www.webcodegeeks.com/web-development/clean-code-principles-better-programmer/ ----------- ...

  8. 《clean code》讲述代码中的道,而不是术

    Clean code 看<clean code>一书,学习高手写出的代码,简单高效的代 1.目标 Bjarne Stroustrup:优雅且高效:直截了当:减少依赖:只做好一件事 Grad ...

  9. 代码整洁之道Clean Code笔记

    @ 目录 第 1 章 Clean Code 整洁代码(3星) ?为什么要整洁的代码 ?什么叫做整洁代码 第 2 章 Meaningful Names 有意义的命名(3星) 第 3 章 Function ...

随机推荐

  1. php 用户验证的简单示例

    发布:thebaby   来源:net     [大 中 小] 本文介绍下,在php中,进行用户登录验证的例子,这个是基于WWW-Authenticate登录验证的实例,有需要的朋友参考下吧. 大家是 ...

  2. Yii 配置默认controller和action

    设置默认controller 在/protected/config/main.php添加配置 <?php return array( 'name'=>'Auto', 'defaultCon ...

  3. 免费使用的图表控件XML/SWF Charts 5.08

    免费使用的图表控件XML/SWF Charts 5.08 http://www.pin5i.com/showtopic-26053.html 10个免费的在线统计图表工具 http://paranim ...

  4. centos系统python升级2.7.3

    首先下载源tar包 可利用linux自带下载工具wget下载,如下所示: wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz 下载 ...

  5. 2014年辛星完全解读Javascript第二节

    本小节我们讲解一下Javascript的语法,虽然js语言非常简单,它的语法也相对好学一些,但是不学总之还是不会的,因此,我们来一探究竟把. ********注释************* 1.我们通 ...

  6. 一个优秀php程序员应具备什么样的能力

    1:php能力 1.1 熟悉 一种或者几种框架,并可以用于开发 1.2 了解 这些框架中的优点与缺点 1.3 假如要你选择框架,你会使用哪种最适合你开发 2:数据库能力 2.1:能写一些简单的sql语 ...

  7. Win10 IIS以及ASP.NET 4.0配置问题日志

    问题日志 升级到Win10并安装了VS2015后,原有ASP.NET 4.0项目在本机的IIS部署出现问题. 安装IIS: 在[控制面板.程序.启用或关闭Windows功能.Internet Info ...

  8. java代码整理---正则表达式

    1. 邮箱验证 : package javaRegx2016311; import java.util.regex.Matcher; import java.util.regex.Pattern; p ...

  9. WebKit Web Inspector增加覆盖率分析和类型推断功能

    WebKit中的Web Inspector(Web检查器)主要用于查看页面源代码.实时DOM层次结构.脚本调试.数据收集等,日前增加了两个十分有用的新功能:覆盖率分析和类型推断.覆盖率分析工具能够可视 ...

  10. ZOJ - 3195 Design the city

    题目要对每次询问将一个树形图的三个点连接,输出最短距离. 利用tarjan离线算法,算出每次询问的任意两个点的最短公共祖先,并在dfs过程中求出离根的距离.把每次询问的三个点两两求出最短距离,这样最终 ...