Building Maintainable Software, Java Edition
by Joost Visser, Sylvan Rigal, Rob van der Leek, Pascal van Eck, Gijs Wijnholds
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:
publicclassCheckingAccount{privateinttransferLimit=100;publicTransfermakeTransfer(StringcounterAccount,Moneyamount)throwsBusinessException{// 1. Check withdrawal limit:if(amount.greaterThan(this.transferLimit)){thrownewBusinessException("Limit exceeded!");}// 2. Assuming result is 9-digit bank account number, validate 11-test:intsum=0;for(inti=0;i<counterAccount.length();i++){sum=sum+(9-i)*Character.getNumericValue(counterAccount.charAt(i));}if(sum%11==0){// 3. Look up counter account and make transfer object:CheckingAccountacct=Accounts ...
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