Skip to Content
程序员的38堂成长课
book

程序员的38堂成长课

by Pete Goodliffe
January 2022
Beginner to intermediate
314 pages
6h 55m
Chinese
Posts & Telecom Press
Content preview from 程序员的38堂成长课
写更少的代码
19
3.3
 重复代码
不必要的代码重复是万恶之源,这种“罪行”最常见的“犯罪”方式就是
复制
/
粘贴式
程。懒惰的程序员不想把一段重复的代码抽取成公有函数,而是直接把它从一个地方复制
到另外一个地方来使用。通常这种“罪行”还会对复制的代码进行细微的修改。
当复制一段代码的同时,你也复制了代码当中的
bug
。哪怕有朝一日,代码中的
bug
被修
复了,系统中还隐藏着未知数量的同一种
bug
,在黑暗中对你虎视眈眈。你应该把重复的
代码重构成一个可以共用的函数。如果重复的部分有细微的差别,可以通过可配置的参数
来进行区分。
要诀
不要复制代码。把重复的代码提取到一个公有函数中,通过参数来控
制变化的部分。
请牢记
DRY
原则:
Don
t Repeat Yourself
(不要重复你自己!)我们的目标符合
DRY
原则——消除重复代码。值得注意的是,将重复的代码提取到一个公有函数中会提高代码
的耦合性。现在有其他的代码也依赖于公有函数的接口,如果对其进行修改,那么所有调
用该函数的地方都需要修改。在很多情况下这是可以接受的。但是也有特殊情况出现,比
如某些长期运行的服务程序可能更倾向于复制代码而不是提取公有函数。
不是所有的代码重复都由懒惰的程序员造成,也可能是意外。某人在不知情的情况下重新
发明了一个轮子,或是构建了一个新功能,而不知道已经有第三方库可以提供该功能。这
种情况可不好,因为现有的库更有可能是正确的,并且已经进行了调试。尽量使用公共库
来减少工作量,同时也能避免新代码带来的潜在
bug
此外,也存在非常微观的代码重复模式,举例如下: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python应用开发指南

Python应用开发指南

Posts & Telecom Press, Ninad Sathaye
解密金融数据

解密金融数据

Justin Pauley

Publisher Resources

ISBN: 9787115577948