1.Do one thing
"FUNCTIONS SHOULD DO ONE THING . THEY SHOULD DO IT WELL .THEY SHOULD DO IT ONLY"
2.One Level of Abstraction per Function
try to keep one level of abstraction per function.Mixing levels of abstraction within a function is always confusing.
3.Switch statements.
switch statements 是很难保证只做一件事,因为很很多个case.
尽量保持用低级别的类和避免代码重复
4.Flag Arguments
最好不要写带标志变量的函数。如果要写,把它拆分为one thing function.
例如: render(boolean isSuite) => renderForSuite() 和 renderForSingleTest()
5.关于函数的参数个数
0 > 1 > 2....
参数越多,就要多花时间记住对应的参数,从而使人容易忘记。如果参数大于2个以上,可以考虑用对象替换参数。
例如:
Circle makeCircle(double x, double y, double radius);
Circle makeCircle(Point center, double radius);
6.不能在一个函数里做其他隐蔽的事
例如:public class UserValidator {
private Cryptographer cryptographer;
public boolean checkPassword(String userName, String password) {
User user = UserGateway.findByName(userName);
if (user != User.NULL) {
String codedPhrase = user.getPhraseEncodedByPassword();
String phrase = cryptographer.decrypt(codedPhrase, password);
if ("Valid Password".equals(phrase)) {
Session.initialize();
return true;
}
}
return false;
}
}
这里的Session.initialize()明显是有悖于函数checkPassword的初衷,很容易让调用者迷惑。
7.避免使用参数作为输出。作为oop编程,输出可用this来传递。
public void appendFooter(StringBuffer report)
转为:report.appendFooter() 更合理
8.函数返回异常比错误码好
if (deletePage(page) == E_OK) {
if (registry.deleteReference(page.name) == E_OK) {
if (configKeys.deleteKey(page.name.makeKey()) == E_OK){
logger.log("page deleted");
} else {
logger.log("configKey not deleted");
}
} else {
logger.log("deleteReference from registry failed");
}
} else {
logger.log("delete failed");
return E_ERROR;
}
改为:
try {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
catch (Exception e) {
logger.log(e.getMessage());
}
这样看来比较简单,另外由于try-catch代码块比较丑,可以提取出来做为一个函数,如下:
public void delete(Page page) {
try {
deletePageAndAllReferences(page);
}
catch (Exception e) {
logError(e);
}
}
private void deletePageAndAllReferences(Page page) throws Exception {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
private void logError(Exception e) {
logger.log(e.getMessage());
}
9.避免重复的代码,同时尽量保持函数只有一个入口和一个出口,只有一个return,没有brea, continue和goto语句。