Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The Refactoring Xplorer - ATBDX 2025

The Refactoring Xplorer - ATBDX 2025

Supports de présentation utilisés pour la session de serious game Refactoring Xplorer lors de l'Agile Tour Bordeaux 2025
Télécharger le jeu : https://insidegroup.fr/ressources/serious-game-clean-code/

Avatar for Julien VITTE

Julien VITTE

October 30, 2025
Tweet

More Decks by Julien VITTE

Other Decks in Programming

Transcript

  1. 4 MAINTENANT DANS 2 SPRINTS AU PROCHAIN SPRINT Sequence.Init(Coords(25, 32),

    "S", "LFRRF"); 1 curl -​ d "LFRRF" -​ X POST https://mars-​ rover/commands 2 var rover = aRover().LandedAt(25, 32).Facing("S"); 3 rover.Move("LFRRF"); 5 while (!sequence.IsComplete()) sequence.Next(); 6 report.Should().Be("25:32:W"); Votre terrain de jeu
  2. Une méthode contient trop de lignes de code. Généralement, toute

    méthode de plus de dix lignes devrait vous inciter à vous poser des questions. LONG METHOD +3 WITH TOO MANY PARAMETERS BLOATERS QUAND ? Impact sur le temps de réalisation Nom CODE SMELLS maintenant au prochain sprint dans 2 sprints Vous avez un fragment de code qui peut être regroupé. Déplacez ce code dans une nouvelle méthode distincte et remplacez le code d'origine par un appel à la méthode. EXTRACT METHOD SOLUTION 2 21 REFACTORING OPTIONS Pour isoler un bloc switch et le placer dans la bonne classe, utilisez Extract Method et Move Method Le bloc switch est basé sur une ou plusieurs constantes utilisez Replace Type Code with Subclasses ou Replace Type Code with State/Strategy Après avoir spécifié la structure d'héritage, utilisez Replace Conditional with Polymorphism pour remplacer les conditions par du polymorphisme. La capacité de sprint baisse de 10 points Vous perdez temporairement 3 cartes refactoring BUS FACTOR maintenant Absence imprévue d'un membre de l'équipe REFACTORINGS ÉVÉNEMENTS FONCTIONNALITÉS Catégorie Problème Résolution Résolution Problème Nom Temps de réalisation Titre Temps de réalisation Valeur produite Impact Contexte peut nécessiter plusieurs compétences de refactoring Votre matériel
  3. Poor INTERNAL quality. Code that’s hard to work with Technical

    debt Additional effort and work required to complete any software development. a systematic process of improving code without creating new functionality that can transform a mess into clean code and simple design. Refactoring Find a code smell Apply a process Code is cleaner Code smells highlighted by indicators of problems in the code base easy to spot and fix may be just symptoms of a deeper problem with code. treated with The code should become cleaner. ✓ The code's behavior must not change (from the user 's perspective) ✓ All existing tests must pass after ✓ Checklist What are we talking about?
  4. a systematic process of improving code without creating new functionality

    that can transform a mess into clean code and simple design. Refactoring Outcomes Code cheaper to modify Code easier to understand When ? A necessary part of iterative and incremental development. You can’t plan the entire design up front You take working code and change the design to support new functionality. Before working on legacy code or code with technical debt Safe refactoring Reduce complexity Improve readability Refactoring Since two refactorings R1 and R2 each leave the code behaving the same but with different, presumably improved design, then R1•R2 is also a refactoring, all the way up to replacing all the code.
  5. Always leave the campground cleaner than you found it. If

    you find a mess on the ground, clean it up regardless of who might have made the mess. — Robert C. Martin Find smells in the code you're editing Apply refactoring to clean the code 1. 2. Avant toute modification du code Une fois la fonctionnalité terminée Refactoring: not in the backlog Time Refactroing as a day to day process Enabler #1 : Boyscout Rule CLEAN CODE Leave your code better than you found it. BOYSCOUT RULE
  6. Code smells are parts of code that suffer from structural

    antipatterns: the code is correct but not structured in a way that is easy to process. Code smells harm cognition SWITCH STATEMENTS OBJECT-​ ORIENTATION ABUSERS BLO ATERS Une méthode est surchargée de commentaires explicatifs. Un opérateur sw itch complexe ou une séquence d'instructions if LONG METHOD BLO ATERS Une méthode contient trop de lignes de code. Généralement, toute méthode de plus de dix lignes devrait vous inciter à vous poser des questions. DATA CLUMPS DISPENSABLES Parfois, différentes parties du code contiennent des groupes identiques de variables. Ces groupes devraient être encapsulés en leurs propres classes LARGE CLASS DUPLICATED CODE DISPENSAB LES Deux fragments de code se ressemblent presque à l'identique. NO POSSIBILITY FOR EFFICIENT CHUNKING OVERLOADING THE CAPACITY OF THE WORKING MEMORY CHUNKING GONE WRONG COMMENTS DISPENSAB LES Une méthode est surchargée de commentaires explicatifs. CAN TRICK YOUR INTUITIVE SYSTEM
  7. Refactorings ? Reverse refactoring Cognitive refactoring aims to make the

    code easier to grasp for the current reader, even if it reduces overall maintainability. Find a code smell Apply a process Code is cleaner The code should become cleaner. ✓ The code's behavior must not change (from the user 's perspective) ✓ All existing tests must pass after ✓ Checklist a temporary action to understand the code right now. It’s an exploratory tool, not a change meant to remain. Scratch refactoring The goal is to get familiar with the code, not to actually clean it: you perform experimental refactoring without the constraint of preserving behavior exactly. The only rule is: revert your changes when you’re done.
  8. Different Goals: Better code quality: Improve internal code quality and

    maintainability (such as readability, uniformity, and understandability) Finding defects: Improve quality regarding external aspects, especially correctness, but also find issues such as performance problems, security vulnerabilities, and injected malware Increase sense of mutual responsibility: Increase a sense of collective code ownership and solidarity, reduces Bus Factor Finding better solutions: Generate ideas for new and better solutions and ideas that transcend the specific code at hand Learning/Knowledge transfer: Help transfer codebase knowledge, solution approaches, and quality expectations, both to the reviewers and the author The review process should not be unnecessarily complex Examining the produced code from an outside perspective Prefer a synchronous code review to lengthy written comments Code review is only useful if the defects found are corrected Code written in pairs or mob programming is code that has already been reviewed Enabler #2 : Code review
  9. 7 vars (attributes / properties / temp) 7 actions 7

    concepts 7 slots for your STM Code That Fits in Your Head https://www.oreilly.com/library/view/cod e-​ that-​ fits/9780137464302/ Main Other things A fractal approach Refactoring Model : Hex Flower
  10. class OrderCreationUseCase { public function __construct( private OrderRepository $orderRepository, private

    ProductCatalog $productCatalog ) { } public function run(SellItemsRequest $request): void { $order = new Order(OrderStatus::CREATED, [], 'EUR', 0, 0); foreach ($request->getRequests() as $itemRequest) { $product = $this->productCatalog->getByName($itemRequest->productName); if ($product === null) { throw new UnknownProductException(); } $unitaryTax = round($product->price / 100 * $product->category->taxPercentage, 2); $unitaryTaxedAmount = round($product->price + $unitaryTax, 2); $taxedAmount = round($unitaryTaxedAmount * $itemRequest->quantity, 2); $taxAmount = $unitaryTax * $itemRequest->quantity; $orderItem = new OrderItem($product, $itemRequest->quantity, $taxAmount, $taxedAmount ); $order->items[] = $orderItem; $order->total += $taxedAmount; $order->tax += $taxAmount; } $this->orderRepository->save($order); } } order request product EUR OrderStatus:: Created unitaryT ax unitaryT axedAm ount taxedA mount taxAm ount orderItem 0 orderRepository productCatalog 100 2 itemRequest [] Refactoring Model : Hex Flower
  11. Technical Debt Radar Y: level of pain when working with

    a specific part of the codebase. + PAIN - PAIN + Dev time - Dev time Login Search DI Share Http clients Aggregation Hotspots “If the code never changes, it’s not costing us money” — Sandi Metz The Wall of Technical Debt Login Search DI Share Http clients Aggregation L XL M S L S Domain Technical Make It Visible Pick a wall in the space where your team works. Make sure it’s publicly visible. Label it the “Wall of Technical Debt.” Draw a nice dramatic logo. Make sure there are sticky notes and markers around so people can easily add to it. Build a Habit Whenever you work on code and encounter technical debt: Write down any technical debt you encountered on a sticky note Estimate the opportunity cost, i.e. the time you would have spent on something else if the issue at hand didn’t exist. Estimate how long it would take to fix it, and write that down as well. Negotiate Regularly The point is not to fix all technical debt. The point is to learn to negotiate when to add it, when to fix it, and when to avoid it. X: how much development time would it take to improve the mentioned piece of code. Enabler #3 : Prioriser le remboursement de la dette
  12. Examine 1 Prepare Improve Clear 2 3 4 find the

    program element(s) you want to transform. (AKA Identify). before you do the transformation, work on making that change easier. This can mean researching the impact of the planned change, or doing some preparatory refactorings to make it easier. follow safe steps to complete the design transformation. (AKA Refactor, Improve). remove any preparations or scaffolding that is not needed now the refactoring is completed. (AKA Clean). EPIC Refactoring Reverse refactoring Cognitive refactoring REFACTORING Examine Prepare Implement Clear EPIC CLEAN CODE 7 concepts / actions / vars to write Code that fits in yor head HEX FLOWER
  13. Improved Refactoring Checklist At most one test should fail on

    each step the Strangler Fig pattern The huge strangler figs grows into fantastic and beautiful shapes, meanwhile strangling and killing the tree that was their host => Progressively delete the old code base, in favor of a new one. Have the new code acts as a proxy for the old code. Users use the new system, but it just redirects to the old one. Re-​ implement each behavior to the new codebase, with no change from the end-​ user perspective. Progressively fade away the old code by making users consume the new behavior. Delete the old, unused code. 1. 2. 3. How To ? Create your code somewhere else. Unit test it. Identify where you should call that code from the existing code: the insertion point. Call your code from the Legacy Code. 1. 2. 3. 4. SPROUT TECHNIQUE Rename the old method you want to wrap. Create a new method with the same name and signature as the old method. Call the old method from the new method. Put the new logic before/after the other method call. Inline the old method 1. 2. 3. 4. 5. Wrap TECHNIQUE Adapt a green test to new incoming code make the test pass remove old tests Always green refactoring REFACTORING - Create new code somewhere else. - Unit test it. - Identify where you should call that code from the existing code - Call your code from the Legacy SPROUT TECHNIQUE REFACTORING - Rename the method. - Create a method with same name and signature. - Call the old method from the new one and put the new logic before/after the other method call. WRAP TECHNIQUE REFACTORING Gradually create new code around the edges of the old one. STRANG LER FIG The code should become cleaner. ✓ The code's behavior must not change (from the user 's perspective) ✓ All existing tests must pass after ✓ How to deal with Large refactorings ?