Rewrite Legacy Code
Legacy code can be a significant challenge in any project. It often lacks tests, contains obsolete logic, and is difficult to maintain. The urge to rewrite such code from scratch can be strong, but it’s essential to take a structured approach to ensure that you don’t introduce new bugs or lose the original business logic.
Understand and Cover the Current Behavior
Before changing any line of legacy code, you need to understand its current behavior. This means thoroughly investigating what the system does. The first step is to write tests around the existing functionality.
Here’s a Java example on the banking domain:
publicclassTransactionService{publicvoidmove(Accountfirst,Accountsecond,doubleamount){if(first.getBalance()<amount){thrownewInsufficientFundsException("Not enough funds in source account");}first.debit(amount);second.credit(amount);}}
In this code, the logic transfers funds between two bank accounts. Although simple, imagine this is embedded within hundreds of other lines, making it hard to isolate.
You can start by writing tests for this behavior without actually changing the legacy code in the same way you do when addressing bugs (see “Fix Bugs in a Continuous Integration Pipeline” in this Shortcut series):
classTransactionServiceTest{@TestvoidshouldTransferFundsBetweenAccounts(){Accountsource=newAccount(1000.0);Accounttarget ...
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