Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Rewriting 15-Year-Old Code
Search
Anna Filina
October 17, 2017
Programming
420
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Rewriting 15-Year-Old Code
Anna Filina
October 17, 2017
More Decks by Anna Filina
See All by Anna Filina
Surviving a Symfony Upgrade
afilina
1
210
Upgrading Legacy to the Latest PHP Version
afilina
1
230
Better Code Design in PHP
afilina
0
330
Semi-Automated Refactoring and Upgrades with Rector
afilina
0
220
Better Code Design in PHP
afilina
1
490
Better Code Design in PHP
afilina
0
650
Adding Tests to Untestable Legacy Code
afilina
0
440
Upgrading Legacy to the Latest PHP Version
afilina
0
450
Semi-Automated Refactoring and Upgrades with Rector
afilina
0
360
Other Decks in Programming
See All in Programming
iOS開発×AI駆動開発 〜最近使って便利だったスキルの話〜
nogu66
0
140
{ Android | Kotlin } Gradle Plugin in 2026
ryunen344
1
270
Building an Out-of-Order CPU
latte72
0
590
書籍「プロフェッショナルAI駆動開発」紹介スライド
juntaromatsumoto
0
960
FastAPI の並行処理モデルを完全に理解する
hoto17296
9
3.7k
関東Kaggler会_NVIDIA_Nemotron_コンペ_振り返り
rick_ds
0
810
Vibes Containers 〜AIで変わるコンテナ設計と運用〜
tkikuc
1
430
ハーネス設計入門 〜プロンプト、コンテキストの次〜
kinopeee
53
34k
源内ハンズオン概要編
hideg
0
240
型解析で実現する Go の言語内 DSL / Conference に Go! タイムテーブルの歩き方 for Gophers
mazrean
0
110
ソフトウェアエンジニアにとっての生成AI - 特性を知って使い倒す / generative ai for software enginner
kishida
7
2.3k
週末にAI-DLCを本気で回したら$1,600溶けた
hbashimizu
0
120
Featured
See All Featured
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
9
1.5k
Building Adaptive Systems
keathley
44
3.2k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
760
Technical Leadership for Architectural Decision Making
baasie
3
550
Visualization
eitanlees
152
17k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
141
35k
GitHub's CSS Performance
jonrohan
1033
470k
Keith and Marios Guide to Fast Websites
keithpitt
413
23k
Discover your Explorer Soul
emna__ayadi
2
1.3k
The State of eCommerce SEO: How to Win in Today's Products SERPs - #SEOweek
aleyda
2
11k
Art, The Web, and Tiny UX
lynnandtonic
304
22k
Site-Speed That Sticks
csswizardry
13
1.5k
Transcript
@afilina Rewriting 15-Year-Old Code Mtl.rb - October 17, 2017
Anna Filina • Project rescue expert • Legacy fixer •
Developer • Conference speaker • Trainer
You inherited a 17-year-old codebase Code doesn't age like wine.
The Web Was 600px Wide
Feeling Old Yet? • Y2K bug. • Internet Explorer 5.
• ICQ was starting to be cool. • Rounded corners = status symbol.
Code smells
Mixed Concerns <% products = Product.all total = 0 products.each
do |product| total += product.qty * product.price end %> <p>Total: <%= total %></p>
Poorly Named Variables a = #... array = #... item3
= #...
Global Functions & Constants require_relative '../../functions.rb' MyClass::my_method(param) # namespaced function?
my_method(DEV_MODE)
Inexplicable Conditions if order_id > 20117 # use this sql
else # use that sql end # weakness = time to refactor
Long Methods public function importCsv($path, $googleApiKey, $databaseDsn, $databaseUser, $databasePassword) {
// Convert CSV to array of conferences $lines = file($path); $csv = array_map('str_getcsv', $lines); $conferences = []; foreach ($csv as $line) { $conference = new Conference(); $conference->name = $line[0]; $conference->location = $line[1]; $conferences[] = $conference; // Get coordinates for location $location = urlencode($conference->location); $url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.$location.'&key='.$googleApiKey; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); curl_close($curl); $json = json_decode($response); if (count($json->results) == 0) { continue; } $latitude = $json->results[0]->geometry->location->lat; $longitude = $json->results[0]->geometry->location->lng; $coordinates = $latitude.','.$longitude; $conference->coordinates = $coordinates; // Save conference to database $pdo = new PDO($databaseDsn, $databaseUser, $databasePassword); $statement = $pdo->prepare('REPLACE INTO conference (name, location, coordinates) VALUES (?, ?, ?)'); $statement->execute([ $conference->name, $conference->location, $conference->coordinates, ]);
Average Legacy Code File • 3000-6000 lines of code. •
Half of it is commented "in case we need it later". • Method length of 800 lines. • Abuse of helper classes. • Sometimes no classes at all.
Codebase • 5,000 classes. • 20,000 methods. • 1,500,000 lines
of code.
Before you code
Strategy • Make a strategy based on constraints. • Full
rewrite vs progressive: ◦By class. ◦By feature. ◦By HTTP call. • How to run code side-by-side: ◦DB/Session sharing. ◦mod_rewrite.
Data Can Be Lost, Stuff Can Break • Backup: test
restore. • Nullify sensitive data. • Staging: simulate deployments/ upgrades/batch processes. • Automate tests before code changes. • Make a risk assessment: ◦ Don't be too optimistic. ◦ Account for side-effects.
Build With Real Legacy Data
(Failed) rewrite example
PHP 3 to PHP 5.6 • HTML + PHP +
SQL in same file. • Includes all over the place. • IFs that concatenate SQL. • Previous rewrite attempt: ◦ Failed, made things worse. ◦ Folders of dead code. ◦ Classes with static functions (no instances).
Solution • Rewrite complex forms using a framework: ◦ mod_rewrite
for concerned pages. • Rewrite biggest feature as OOP: ◦ Design extraction. ◦ Flexible architecture. ◦ Automated tests.
New feature should not take longer than a sprint.
Design extraction
Avoid Code Bias • Old code → design docs. •
Validate design docs: ◦Clarify business rules. • Improve design: ◦Reduce technical debt. ◦More flexible. • Design docs → new code.
Fixing bugs
Code Duplication • Sometimes, the bug is repeated 80+ times.
• Remove duplications ASAP.
Fix Long Methods • Extract broken part into its own
method. • Write unit tests for it. • Fix it. • Call it from the mega-method.
Spot Logical Groups Code block Comment Code block Comment Convert
CSV to array of conferences. Get coordinates for conference location. Save conference to database. Code block Comment
Extract & Test Code block Comment Code block Method Code
block Comment Call method
Name Code block Method Code block Method Call method Call
method Code block Method Call method conferences_from_csv location_coordinates save_conference
Rewrite example #2
ASP Classic to PHP 5.6 • 15+ spaghetti and hacks.
• Language no longer supported. • Huge ERP with lots of code.
Solution • Rewrite page by page to a framework. •
mod_rewrite for concerned pages. • DB session adapter in both apps. • Page in any language = HTTP request. ◦ Automated testing possible!
HTTP Tests
On Testing Before you code You better test So that
on weekends You may rest. -- Me
Stuck?
None
Try Something New • Bounce ideas. ◦ New people to
avoid tunnel vision. • Has this been done before? • Can I try another approach?
Takeaways • Make a strategy. • You touch it, you
refactor it. • Use known tools & methodologies. • Get inspiration from others. • Refactoring gets easier. • Every problem has a solution.
Refactoring: Improving the Design of Existing Code Martin Fowler
@afilina afilina.com joind.in