
WTF/min 是衡量代码质量的惟一标准,Uncle Bob 在书中称糟糕的代码为沼泽(wading),这只突出了咱们是糟糕代码的受害者。html
国内有一个更适合的词汇:屎山,虽然不是很文雅可是更加客观,程序员既是受害者也是加害者。前端
对于什么是整洁的代码,书中给出了大师们的总结:程序员
Bjarne Stroustrup:优雅且高效;直截了当;减小依赖;只作好一件事web
Grady booch:简单直接算法
Dave thomas:可读,可维护,单元测试express
Ron Jeffries:不要重复、单一职责,表达力(Expressiveness)编程
命名的艺术后端
下面是书中的一个示例代码,展现了命名对代码质量的提高:微信
# bad code
def getItem(theList):
ret = []
for x in theList:
if x[0] == 4:
ret.append(x)
return ret
# good code
def getFlaggedCell(gameBoard):
'''扫雷游戏,flagged: 翻转'''
flaggedCells = []
for cell in gameBoard:
if cell.IsFlagged():
flaggedCells.append(cell)
return flaggedCells
不要挂羊头卖狗肉,不要覆盖惯用缩略语!架构
代码是写给机器执行,也是给人阅读的,因此概念必定要有区分度:
# bad
def copy(a_list, b_list):
pass
# good
def copy(source, destination):
pass
注释
The proper use of comments is to compensate for our failure to express ourself in code.
书中给出了一个很是形象的例子来展现,用代码来阐述,而非注释:
bad
// check to see if the employee is eligible for full benefit
if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))
good
if (employee.isEligibleForFullBenefits())
法务信息
对意图的注释,为何要这么作
警示
TODO 注释
放大看似不合理之物的重要性
函数
好比书中的例子:
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;
}
}
好比咱们想把大象放进冰箱,应该是这个样子的:
def pushElephantIntoRefrige():
openRefrige()
pushElephant()
closeRefrige()
某种程度看来,这个跟金字塔原理也很像:
测试
可读性
可读性
可读性
对于测试的原则、准则以下:
没有测试以前不要写任何功能代码
只编写刚好可以体现一个失败状况的测试代码
只编写刚好能经过测试的功能代码
快速(Fast)测试应该够快,尽可能自动化。
独立(Independent)测试应该应该独立。不要相互依赖
可重复(Repeatable)测试应该在任何环境上都能重复经过。
自我验证(Self-Validating)测试应该有 bool 输出。不要经过查看日志这种低效率方式来判断测试是否经过。
及时(Timely)测试应该及时编写,在其对应的生产代码以前编写。
做者:xybaby
出处:https://www.cnblogs.com/xybaby/p/11335829.html
文末彩蛋
编程·思惟·职场
欢迎扫码关注
本文分享自微信公众号 - 前端迷社区(gh_c8466b051727)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。