惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
Cyberwarzone
Cyberwarzone
L
LINUX DO - 最新话题
N
News and Events Feed by Topic
T
Troy Hunt's Blog
Help Net Security
Help Net Security
S
Security @ Cisco Blogs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
M
MIT News - Artificial intelligence
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V2EX - 技术
V2EX - 技术
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
Cisco Talos Blog
Cisco Talos Blog
T
Threatpost
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
SegmentFault 最新的问题
I
InfoQ
H
Hacker News: Front Page
D
Docker
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Blog — PlanetScale
Blog — PlanetScale
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
N
Netflix TechBlog - Medium
AWS News Blog
AWS News Blog
Know Your Adversary
Know Your Adversary
博客园 - 【当耐特】
T
Tor Project blog
U
Unit 42
H
Heimdal Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Privacy & Cybersecurity Law Blog
PCI Perspectives
PCI Perspectives
美团技术团队
O
OpenAI News
T
Tailwind CSS Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog
GbyAI
GbyAI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MyScale Blog
MyScale Blog

Yusuf Aytas

When Code Is Cheap, Does Quality Still Matter? Why Crouching Tiger, Hidden Dragon Is a Masterpiece Why We Ignore Advice The Mirror Is Part of the Machine When Too Many Maps Overlap on One Person The Work Runs on Different Maps Your Work Introduces You Trial By Fire The Dude Why Headcount Math Lies Capacity Is the Roadmap The Roadmap Is Not the System Torres del Paine W Trek Escaping Status Theater Incentives Drive Everything Scaling Culture Without Dilution What Good Looks Like Why Airport Security Feels Random Why Politics Appear How to Work with Me The Janus Protocol Multi-Horizon Delivery Framework What Good Execution Looks Like Managing Your Manager Why Kingdom of Heaven’s Director’s Cut Is Better AI Broke Interviews Most of What We Call Progress Managers Have Been Vibe Coding All Along Stop Wasting Brainpower Why Over-Engineering Happens Prisoner's Dilemma Climbing No More The Weekly Win Mevlana Candy Brewing Turkish Tea Onboarding Your Engineering Manager Technical Deep Dives Yapay Zekâ Çağında Bilgisayar Mühendisliği Building Remote Teams From Idea to Launch in 2 Weeks Reflecting on Software Engineering Handbook Representing the Business New Manager Survival Guide Take Self Reviews Seriously Chasing Real Respect The Invisible Difference Learning the Johari Window Management is a Lonely Place Simple Task Management AI Balance in Work PIP Manager Insights Engineering Manager Interview Preparation Work-Life Balance as a Manager Bridging the Management Disconnect Tech Hiring Bubble Bursts Traits for EMs Simple Acts of Recognition Matter The Question I Ask Every New Report The Reality of an Employer's Market Bridging Ideals and Reality Hiring Red Flags Why The Godfather Is So Damn Good Subteam Tenets No Fluff Please Losing a Top Performer Balancing Act of Reliability Building Trust in Engineering Teams Ideal Number of Direct Reports Overriding a People Leader’s Decision From Misperception to Promotion Perception vs Perspective Setting Goals From Engineer to Manager Getting Delegation Right Interviewing Your Future Boss Celebrating Our Book in Iceland Operational Skills Needed On Writing Software Engineering Handbook Charlie Munger Quotes Working with Dependencies From Las Vegas to Canyons Navigating Layoffs Handling Competitive Dynamics A Weekend Getaway to Malta Engineering Health Essentials Should Dev Managers Code? Confronting the Life on Pause Winning Eleven Kindness is A Choice Bireysel Katılımcılar ve Yöneticiler Leading from Where You Are The Subtle Art of Listening Coding in Leadership The Power of Consistency The Making of a Leader The Path to Leadership Embracing TikTok Talent Sourcing Journey Leading Self Managing Teams Cracking Coding Bottlenecks
Duplicate code isn't that bad
Yusuf Aytas · 2017-04-12 · via Yusuf Aytas

Published · 4 min read

Duplicate code isn’t something we usually want in our code for various reasons. The most obvious one is maintenance. When you change a piece of logic, you have to find every place where it appears and update them all. A deeper reason lies in the proper use of design principles, such as Don’t Repeat Yourself (DRY). Although it’s hard to argue against these ideas, I still believe duplicate code can sometimes be acceptable. Sometimes it's even helpful.

Over the years, I have learned that a little duplication can make your code more readable and understandable. While DRY teaches us to avoid repetition, our real goal isn’t to follow the rule itself. The real goal is maintainability and clarity. DRY is a tool, not a religion.

Code duplication is not that badCode duplication is not that bad

Readability Often Matters More

If duplication improves readability, it might actually serve that goal better. One of the clearest examples is setup code in testing. You could technically extract helper functions, but doing so can make tests harder to read because the reader has to jump between files or methods to understand what data is being created. Sometimes, keeping that code inline makes it easier to see what is happening.

For example:

@Test
public void calculate(){
  Dog dog = new Dog();
  dog.setName("karabas");
  dog.setAge(3);
  Human human = new Human();
  human.setAge(41);
  human.setDog(dog);
  ...
}

@Test
public void calculateWithSmallerGap(){
  Dog dog = new Dog();
  dog.setName("karabas");
  dog.setAge(3);
  Human human = new Human();
  human.setAge(7);
  human.setDog(dog);
  ...
}

Here, I can clearly see two pieces of duplicated logic — one for creating a Dog and another for creating a Human. I could extract helper functions, but the tests would become less direct. This duplication makes the code easier to follow, so I prefer to keep it that way for a while.

Premature Abstraction Can Be Worse

Removing duplicate code too early is a form of premature optimization. Refactoring for the sake of cleanliness alone can make things worse or lead to unnecessary abstraction. It’s wiser to focus on keeping the code clean and well-tested. When the right time comes, duplication reveals its own refactoring opportunities naturally.

Here’s another example that illustrates this process:

function calculateSimpleSalary(base, bonus, isOverAchieving){
  let total = base + bonus;
  if(isOverAchieving){
     total += (base \* OVER\_ACHIEVING\_PERCENT) / 100;
  }
  return total;
}

function calculateOvertimeSalary(base, bonus, overtime, isOverAchieving){
  let total = base + bonus + overtime;
  if(isOverAchieving){
     total += (bonus \* OVER\_ACHIEVING\_PERCENT) / 100;
  }
  if(isOverAchieving){
     total += (overtime \* OVER\_ACHIEVING\_PERCENT) / 100;
  }
  return total;
}

At first glance, these two functions share obvious similarities. You could create a helper for overachieving salary or reuse logic between them, but at this stage, it might be too soon. The codebase is still young. The duplication is tolerable because it’s easy to understand and test. As the system grows, patterns will emerge, and refactoring will become obvious.

Later, when we add more related logic, the right moment arrives:

function calculateAfterTax(salary, isBonus){
  let tax = isBonus ? (salary \* TAX\_ON\_BONUS) / 100 :  (salary \* TAX\_ON\_BASE) / 100;
  return salary - tax;
}

function calculateAfterTaxSalary(person){
  let totalSalary = calculateAfterTax(base, false) + calculateBonusAfterTax(bonus, isOverAchieving);
  if(person.hasOvertime()){
     totalSalary += calculateBonusAfterTax(person.overtime, person.isOverAchieving);
  }
  return totalSalary;
}

function calculateBonusAfterTax(bonus, isOverAchieving){
  let totalAfterTax = calculateTax(bonus, true);
  if(isOverAchieving){
    totalAfterTax += calculateTax(bonus \* OVER\_ACHIEVING\_PERCENT / 100, true);
  }
  return totalAfterTax;
}

At this point, refactoring makes sense. The duplicated patterns are now stable, and abstraction brings real value.

Let the Code Mature

Duplicate code is not inherently bad. It becomes a problem only when it grows uncontrolled or starts causing inconsistency. In the early stages of development, clarity and stability are more important than elegance.

Principles like DRY, SOLID, and KISS are meant to guide thinking, not limit it. Let your codebase evolve naturally. When duplication starts to feel heavy, that’s when it’s time to refactor, not before.

In conclusion, we can live with duplicate code for a while. Sometimes even longer. While duplication goes against established design principles, those principles are only means to an end. The real goal is to write code that is understandable, maintainable, and easy to change.

Let the code mature. Refactor when the repetition starts to hurt, not when it merely exists.