May 2025
Intermediate to advanced
430 pages
4h 9m
Chinese
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
要知道哪些地方需要检查,并确保程序在出错时能迅速失效,是一门艺术。这种选择是简化艺术的一部分。
沃德-坎宁安
快速失败的能力对于简洁的代码至关重要。一旦业务规则失败,您需要立即采取行动。每一次无声的失败都是一次错失的改进机会。要准确调试问题,您需要找到根本原因。而根本原因会给你一定的提示,让你追踪并解决故障。快速失败的系统比弱小的系统更稳健,弱小的系统会将失败一扫而过,即使失败影响了正确的结果,处理仍会继续进行。
你可以重复使用不同作用域的变量。
不要重复使用变量名。这样做会破坏可读性和重构机会,而且一无所获;这是一种不成熟的优化,不会节省内存。尽可能缩小作用域。
如果重复使用变量并扩展其范围,自动重构工具可能会崩溃,虚拟机可能会错失优化机会。建议您在定义、使用和处置变量时缩短其生命周期。在这个示例中,有两个不相关的购买项目:
classItem:deftaxesCharged(self):return1;lastPurchase=Item('Soda');# Do something with the purchasetaxAmount=lastPurchase.taxesCharged();# Lots of stuff related to the purchase# You drink the soda# You cannot extract method from below without passing# useless lastPurchase as parameter# a few hours later…lastPurchase=Item('Whisky');# You bought another drinktaxAmount+=lastPurchase.taxesCharged();
下面是缩小范围后的结果:
classItem:deftaxesCharged(self):return1;defbuySupper():supperPurchase=Item('Soda');# Do something with the purchase# Lots of stuff related to the purchase# You drink the sodareturnsupperPurchase;defbuyDrinks():# You can extract the method!# a few hours later..drinksPurchase=Item('Whisky');# I bought another drinkreturndrinksPurchase;taxAmount=buySupper().taxesCharged()+buyDrinks().taxesCharged();
重复使用变量是,也被称为 "非上下文复制粘贴 "提示。
Read now
Unlock full access