Building Maintainable Software, C# Edition
by Joost Visser, Sylvan Rigal, Gijs Wijnholds, Pascal van Eck, Rob van der Leek
Chapter 4. Write Code Once
Number one in the stink parade is duplicated code.
Kent Beck and Martin Fowler, Bad Smells in Code
Guideline:
-
Do not copy code.
-
Do this by writing reusable, generic code and/or calling existing methods instead.
-
This improves maintainability because when code is copied, bugs need to be fixed at multiple places, which is inefficient and error-prone.
Copying existing code looks like a quick win—why write something anew when it already exists? The point is: copied code leads to duplicates, and duplicates are a problem. As the quote above indicates, some even say that duplicates are the biggest software quality problem of all.
Consider a system that manages bank accounts. In this system, money transfers between accounts are represented by objects of the Transfer class (not shown here). The bank offers checking accounts represented by class CheckingAccount:
public class CheckingAccount { private int transferLimit = 100; public Transfer MakeTransfer(String counterAccount, Money amount) { // 1. Check withdrawal limit: if (amount.GreaterThan(this.transferLimit)) { throw new BusinessException("Limit exceeded!"); } // 2. Assuming result is 9-digit bank account number, validate 11-test: int sum = 0; for (int i = 0; i < counterAccount.Length; i++) { sum = sum + (9 - i) * (int)Char.GetNumericValue( counterAccount[i]); } if (sum % 11 == 0) { // 3. Look up counter account and make transfer object: CheckingAccount acct = Accounts.FindAcctByNumber(counterAccount); ...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