0%

类型 Type

  • 创建型 Creational

含义 Intent

The intent of the abstract factory pattern is to provide an interface for creating families of related or dependent objects without specifying their concrete classes

阅读全文 »

注释不能美化糟糕的代码 Comments Do Not Make Up for Bad Code

  • 注释是用代码表达意图遭遇的失败

  • 写注释的常见动机之一是糟糕的代码的存在

用代码来阐释 Explain Yourself in Code

清晰的代码本身就能有效表达意图,应避免依赖注释

确实存在代码难以解释逻辑的情况。不幸的是,许多程序员因此认为代码几乎无法成为好的解释手段,这是错误的观点。如

1
2
// check to see if the employee is eligible for full benefits
if (employee.flags && HOURLY_FLAG) && (employee.age > 65))

可以重构为:

1
if (employee.IsEligibleForFullBenefits())

很多时候,简单到只需要创建一个描述了与注释所言同一事物的函数即可。

阅读全文 »

类型 Type

  • 创建型 Creational

含义 Intent

The intent of the factory method pattern is to define an interface for creating an object, but to let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

阅读全文 »

类型 Type

  • 创建型 Creational

含义 Intent

The intent of the singleton pattern is to ensure that a class only has one instance, and to provide a global point of access to it.

阅读全文 »

短小 Small

函数的第一条规则是要 短小,第二条规则是要 更短小

  • 20 行封顶最佳

例子:

1
2
3
4
5
6
7
public static String renderPageWithSetupsAndTearDowns(PageData pageData, boolean isSuite) throws Exception
{
if (isTestPage(pageData)) {
includeSetupAndTeardownPages(pageData, isSuite);
}
return pageData.getHtml();
}
阅读全文 »

名副其实 Use Intention-Revealing Names

如下是较好的例子(既有计量对象,也有计量单位):

1
2
3
4
int elapsedTimInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;
阅读全文 »