返回主题:务实编程实践

知识卡片

普通读书笔记卡 · 3328.b

相似代码未必该共用抽象

理解等级:高级

两处代码看起来相似,并不保证未来会按同一规则变化。过早抽出共用方法后,若两处需求分化,修改共享方法就可能牵连多个调用方,最后形成难以变更的大型工具类。复用前应核对语义与变化方向是否一致;仅为了减少重复代码而共享,可能制造错误抽象。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    原书出处

    参考来源

    - 位置:《Principles of Software Architecture Modernization》第1章《What’s Wrong with Monoliths?》(源文件:`_epub-src/OPS/ch01.xhtml`,归一化正文 [20775:24977)) - 结论依据:原文通过两个需求后来分化、共享方法不断被修改并膨胀的例子,说明强行共用不相同的情境会形成错误抽象。 - 原始内容:Over time, another engineer is faced with a feature request that affects this code, and suddenly they’re faced with a problem: the first implementation needs one version of method 1, and the second now has different requirements. So they choose to go forward and modify the shared method, thinking again that code reuse is the highest good, which is the best choice.