看完《代码整洁之道》以后我受益不浅,但等到本身实践时却很难按照书中给的建议编写出整洁的代码。一方面是规则太多,记不住,另外一方面书上引用了大量示例代码对这些规则进行佐证,在我记不住时亦不方便查阅。因而我把书中的规则摘了出来并加以必定的解释,闲暇时候多过几遍,但愿这些规则时刻警示我,成为个人习惯。php
想看此书却还没开始的人也能够从这篇笔记出发,对笔记中列出的规则有疑问再翻书找答案,相信会比直接啃书来的快一些。java
ps: 未必要严格遵循书中的规则,代码不是八股文。程序员
if(set("username", "unclebob")) { ... }
的含义模糊不清。应该改成:算法
if (attributeExists("username")) { setAttribute("username", "unclebob"); ... }
返回错误码会要求调用者马上处理错误,从而引发深层次的嵌套结构:编程
if (deletePate(page) == E_OK) { if (xxx() == E_OK) { if (yyy() == E_OK) { log(); } else { log(); } } else { log(); } } else { log(); }
使用异常机制:session
try { deletePage(); xxx(); yyy(); } catch (Exception e) { log(e->getMessage()); }
try/catch代码块丑陋不堪,因此最好把try和catch代码块的主体抽离出来,单独造成函数数据结构
try { do(); } catch (Exception e) { handle(); }
建立一个与注释所言同一事物的函数便可并发
// check to see if the employee is eligible for full benefits if ((employee.falgs & HOURLY_FLAG) && (employee.age > 65))
应替换为app
if (employee.isEligibleForFullBenefits())
阐释。把某些晦涩的参数或者返回值的意义翻译成可读的形式(更好的方法是让它们自身变得足够清晰,可是相似标准库的代码咱们没法修改):less
if (b.compareTo(a) == 1) //b > a
// don't run unless you have some time to kill
能用函数或者变量表示就别用注释:
// does the module from the global list <mod> // depend on the subsystem we are part of? if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem())
能够改成
ArrayList moduleDependees = smodule.getDependSubsystems(); String ourSubSystem = subSysMod.getSubSystem(); if (moduleDependees.contains(ourSubSystem))
///////////////////// Actions //////////////////////////
右括号注释
try { while () { if () { ... } // if ... } // while ... } // try
若是你想标记右括号,其实应该作的是缩短函数
/* add by rick */
源代码控制工具会记住你,署名注释跟不上代码的演变。 if (xx == yy) z = 1;
对象:暴露行为(接口),隐藏数据(私有变量)
数据结构:没有明显的行为(接口),暴露数据。如DTO(Data Transfer Objects)、Entity
class C的方法f只应该调用如下对象的方法:
final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
异常处理很重要,但若是异常处理四处分散在代码中 致使逻辑模糊不清,它就是错的。
try { MealExpendses expenses = expenseRepotDAO.getMeals(employee.getID()); m_total += expenses.getTotal();// 若是消耗了餐食,计入总额 } catch (MealExpensesNotFound e) { m_total += getMealPeDiem();// 若是没消耗,将员工补贴计入总额 }
异常打断了业务逻辑。能够在getMeals()里不抛异常,而是在没消耗餐食的时候返回一个特殊的MealExpense对象(PerdiemMealExpense),复写getTotal()方法。
MealExpendses expenses = expenseRepotDAO.getMeals(employee.getID()); m_total += expenses.getTotal(); publc class PerDiemMealExpenses implements MealExpenses { public int getTotal() { //return xxx; //返回员工补贴 } }
将第三方代码干净利落地整合进本身的代码中
四条规矩帮助你建立优良的设计
模板方法模式是消除重复的通用技巧
// 原始逻辑 public class VacationPolicy() { public void accrueUSDivisionVacation() { //do x; //do US y; //do z; } public void accrueEUDivisionVacation() { //do x; //do EU y; //do z; } } // 模板方法模式重构以后 abstract public class VacationPolicy { public void accrueVacation() { x(); y(); z(); } private void x() { //do x; } abstract protected void y() { } private void z() { //do z; } } public class USVacationPolicy extends VacationPolicy { protected void y() { //do US y; } } public class EUVacationPolicy extends VacationPolicy { protected void y() { //do EU y; } }