Java

Decision Guide and Cheatsheet

This final article serves as your comprehensive reference for the entire series. Bookmark it, print it, keep it open while coding. Here you'll find decision trees for pattern selection, quick refactoring recipes, a complete code smell catalog, 50 interview questions, and curated resources for further learning.

📋 At a Glance

AspectDetails
PurposeQuick reference for pattern selection
ContentsDecision trees, cheatsheets, Q&A bank
UsageKeep open while coding, review before interviews
Interview Questions50 questions organized by topic
Best ForFast recall, decision making, interview prep

🎯 What You'll Learn

This reference article provides:

  • Pattern Decision Trees - Flowcharts to choose the right pattern
  • Refactoring Quick Reference - Step-by-step recipes for common refactorings
  • Code Smell → Refactoring Map - What to apply when you detect a smell
  • Interview Questions Bank - 50 senior-level questions with answers
  • IDE Shortcuts - IntelliJ/VS Code refactoring commands
  • Recommended Resources - Books, courses, tools for further learning
  • Complete Series Index - Quick navigation to any topic

🔥 Production Story: The Refactoring Decision Paralysis

A development team had a clear mandate: "Clean up the payment module before Black Friday." They identified 47 code smells across 12 classes. But after two weeks, almost no progress had been made.

The problem? Every code smell led to endless debates:
TEXT(4 lines)
Code
Loading syntax highlighter...
The team was suffering from decision paralysis. Too many options, no clear criteria for choosing between them.
The solution? They created decision trees with objective criteria:
TEXT(5 lines)
Code
Loading syntax highlighter...

With clear decision criteria, the team refactored all 47 smells in one week. This article is that decision guide, refined over years of real projects.


🧠 Mental Model: The Pattern Selection Framework

TEXT(32 lines)
Code
Loading syntax highlighter...

🔬 Pattern Decision Trees

Decision Tree 1: Long Method (> 20 lines)

TEXT(13 lines)
Code
Loading syntax highlighter...

Decision Tree 2: Conditional Logic (switch/if-else)

TEXT(23 lines)
Code
Loading syntax highlighter...

Decision Tree 3: Null Handling

TEXT(26 lines)
Code
Loading syntax highlighter...

Decision Tree 4: Object Creation Complexity

TEXT(24 lines)
Code
Loading syntax highlighter...

Decision Tree 5: Inheritance Problems

TEXT(28 lines)
Code
Loading syntax highlighter...

Decision Tree 6: Exception Handling

TEXT(29 lines)
Code
Loading syntax highlighter...

Decision Tree 7: Legacy Code Refactoring

TEXT(32 lines)
Code
Loading syntax highlighter...

📋 Refactoring Quick Reference

Extract Method

When: Method doing multiple things, comments explaining sections
Steps:
  1. Identify code block to extract
  2. Create new method with descriptive name
  3. Pass needed variables as parameters
  4. Return any modified values
  5. Replace original code with method call
  6. Run tests
IntelliJ: Ctrl+Alt+M (Windows) / Cmd+Option+M (Mac)
JAVA(48 lines)
Code
Loading syntax highlighter...

Extract Parameter Object

When: Method has 4+ related parameters
Steps:
  1. Create new class/record for parameters
  2. Move parameters to new class
  3. Update method signature
  4. Update all call sites
  5. Run tests
IntelliJ: Refactor → Extract Parameter Object
JAVA(21 lines)
Code
Loading syntax highlighter...

Replace Conditional with Strategy

When: Switch/if-else with 4+ cases, especially on type
Steps:
  1. Create Strategy interface
  2. Create implementation for each case
  3. Create factory/registry for strategies
  4. Replace switch with strategy lookup and call
  5. Run tests
JAVA(45 lines)
Code
Loading syntax highlighter...

Introduce Null Object

When: Null checks for same object repeated throughout code
Steps:
  1. Create interface for the object (if not exists)
  2. Create NullObject implementation
  3. Return NullObject instead of null
  4. Remove null checks
  5. Run tests
JAVA(50 lines)
Code
Loading syntax highlighter...

Extract Interface for Testing

When: Class is hard to test due to dependencies
Steps:
  1. Identify methods used by clients
  2. Create interface with those methods
  3. Have class implement interface
  4. Update clients to depend on interface
  5. Create test double implementing interface
  6. Run tests
IntelliJ: Refactor → Extract Interface
JAVA(43 lines)
Code
Loading syntax highlighter...

📊 Code Smell → Refactoring Map

Code SmellSeverityRefactoringArticle
Long Method (> 20 lines)HighExtract MethodPart 6
Large Class (> 200 lines)HighExtract ClassPart 6
Long Parameter List (> 4)MediumParameter ObjectPart 6
Primitive ObsessionMediumValue Object, RecordPart 6, 23
Switch Statements (> 4 cases)MediumStrategy PatternPart 7
Parallel ConditionalsHighStrategy, Template MethodPart 7, 13
Null Checks ScatteredHighNull Object, OptionalPart 8
Telescoping ConstructorMediumBuilder PatternPart 9
Deep Inheritance (> 3 levels)HighCompositionPart 10
Refused BequestMediumDelegationPart 10
Feature EnvyMediumMove MethodPart 6
Inappropriate IntimacyMediumExtract ClassPart 6
Message ChainsLowHide DelegatePart 10
Middle ManLowRemove Middle ManPart 10
Comments Explaining CodeMediumExtract Method (self-documenting)Part 6
Duplicate CodeHighExtract Method/ClassPart 6
Dead CodeLowDelete it-
Speculative GeneralityMediumRemove unused abstraction-
Divergent ChangeHighExtract Class (SRP)Part 2, 6
Shotgun SurgeryHighMove Method, Extract ClassPart 2, 6
Data ClumpsMediumParameter ObjectPart 6
Lazy ClassLowInline Class-
Temporary FieldMediumExtract ClassPart 6
Alternative ClassesMediumExtract Superclass/InterfacePart 6
Incomplete Library ClassLowDecorator, WrapperPart 10

🎤 Interview Questions Bank (50 Questions)

SOLID Principles (10 Questions)

Q1: What is Single Responsibility Principle and how do you identify violations?

Answer: SRP states that a class should have only one reason to change - meaning it should serve only one actor or stakeholder.
Identifying violations:
  • Class has methods serving different stakeholders (e.g., both UI and reporting)
  • Method names suggest different responsibilities ("calculate" and "format")
  • Change requests from different teams affect same class
  • LCOM (Lack of Cohesion) metric is high
Example: UserService with methods like createUser(), sendWelcomeEmail(), generateUserReport() - these serve different actors.

Q2: Explain Open/Closed Principle with a real example.

Answer: OCP states that software entities should be open for extension but closed for modification. You should be able to add new behavior without changing existing code.
Example: Payment processing with Strategy pattern:
JAVA(11 lines)
Code
Loading syntax highlighter...

Q3: What's the Liskov Substitution Principle and what's the classic Rectangle/Square violation?

Answer: LSP states that objects of a superclass should be replaceable with objects of subclasses without breaking the program.
Rectangle/Square violation:
JAVA(17 lines)
Code
Loading syntax highlighter...
Solution: Square is-not-a Rectangle. Use separate classes or immutable shapes.

Q4: When should you apply Interface Segregation Principle?

Answer: Apply ISP when:
  • Clients are forced to implement methods they don't use
  • Interface has methods for multiple different purposes
  • Changes to unused methods force client recompilation
  • Test mocks become complex because of unneeded methods
Example of violation:
JAVA(12 lines)
Code
Loading syntax highlighter...

Q5: What's the difference between Dependency Inversion and Dependency Injection?

Answer:
Dependency Inversion (DIP) - design principle:
  • High-level modules shouldn't depend on low-level modules
  • Both should depend on abstractions
  • Abstractions shouldn't depend on details
Dependency Injection (DI) - implementation technique:
  • Way to provide dependencies to an object
  • Constructor injection, setter injection, field injection
DIP tells you what to do (depend on abstractions). DI tells you how to do it (inject dependencies).

You can have DI without DIP (injecting concrete classes). You can have DIP without DI (factory patterns).


Refactoring Patterns (10 Questions)

Q6: How do you safely refactor a 500-line method?

Answer:
  1. Write characterization tests - capture current behavior
  2. Identify code "paragraphs" - blocks separated by blank lines/comments
  3. Extract one method at a time - start with clearest, most isolated block
  4. Run tests after each extraction
  5. Look for patterns - repeated code → Extract Method
  6. Identify responsibilities - multiple responsibilities → Extract Class
  7. Commit frequently - small, reversible steps
Tools: IntelliJ's Extract Method (Ctrl+Alt+M), automated tests

Q7: When would you use Strategy vs State pattern?

Answer:
Strategy Pattern:
  • Algorithm selection at runtime
  • Strategies are stateless/interchangeable
  • Client chooses the strategy
  • Example: Sorting algorithms, payment methods
State Pattern:
  • Object behavior changes based on internal state
  • States manage transitions to other states
  • Object doesn't know current state details
  • Example: Order status, document workflow
Key difference: Strategy = same input, different algorithms. State = same algorithm, different behavior based on state.

Q8: What's the Null Object pattern and when should you avoid it?

Answer:
Null Object provides an object with default/neutral behavior instead of null.
Use when:
  • Null checks are repeated for same object
  • "No action" is a valid domain behavior
  • Want to simplify client code
Avoid when:
  • Null has specific meaning (error, not found)
  • Masking errors would be dangerous (null in payment = problem!)
  • Object has side effects (logging, persistence)
JAVA(2 lines)
Code
Loading syntax highlighter...

Q9: Explain Builder pattern. When is Step Builder better?

Answer:
Basic Builder: Fluent interface for object construction with many parameters.
Step Builder: Enforces required parameters at compile time by returning different types.
JAVA(8 lines)
Code
Loading syntax highlighter...
Use Step Builder when:
  • Some parameters are required
  • Want compile-time safety
  • API must be foolproof

Q10: How does composition solve the inheritance problems?

Answer:
Inheritance problems:
  • Fragile base class (changes break subclasses)
  • Forced to inherit unwanted behavior
  • Can only inherit from one class
  • Deep hierarchies hard to understand
Composition solves these:
JAVA(11 lines)
Code
Loading syntax highlighter...
Key insight: "has-a" is usually better than "is-a".

Error Handling (10 Questions)

Q11: How do you design a good exception hierarchy?

Answer:
TEXT(11 lines)
Code
Loading syntax highlighter...
Best practices:
  • Extend RuntimeException (unchecked)
  • Include context (error code, correlation ID)
  • Layer-appropriate messages (no SQL errors to users)
  • Exception chaining (preserve root cause)

Q12: When should you use Result pattern vs exceptions?

Answer:
Use Exceptions for:
  • Truly exceptional situations (bugs, infrastructure failures)
  • Unrecoverable errors
  • When caller can't reasonably handle the error
Use Result Pattern for:
  • Expected failures (validation, business rules)
  • When caller must handle the failure
  • Functional programming style
  • Accumulating multiple errors
JAVA(12 lines)
Code
Loading syntax highlighter...

Q13: What is RFC 7807 and why use it?

Answer: RFC 7807 "Problem Details for HTTP APIs" is a standard format for error responses.
Structure:
JSON(8 lines)
Code
Loading syntax highlighter...
Why use it:
  • Industry standard (clients know what to expect)
  • Machine-readable error types (URI)
  • Extensible (add custom fields)
  • Spring 6 has built-in support

Q14: How do you prevent exceptions from leaking sensitive information?

Answer:
  1. Sanitize before logging: Remove credentials, PII
  2. Generic client messages: "An error occurred" (details in logs)
  3. Map internal to external: SQLException → "Database unavailable"
  4. Remove stack traces in production: Only log correlation ID
  5. Review exception messages: No SQL, no file paths
JAVA(8 lines)
Code
Loading syntax highlighter...

Q15: What's exception chaining and why is it important?

Answer: Exception chaining preserves the original cause when wrapping exceptions.
JAVA(9 lines)
Code
Loading syntax highlighter...
Why important:
  • Root cause visible in stack trace
  • Debugging is possible
  • Original exception type available via getCause()
  • Required for proper error analysis in production

Validation (5 Questions)

Q16: Bean Validation vs Fluent Validation - when to use each?

Answer:
Bean Validation (JSR-380):
  • Annotation-based (@NotNull, @Size)
  • Standard, well-supported
  • Good for simple constraints
  • Integrates with Spring MVC
Fluent Validation:
  • Programmatic, composable
  • Complex, conditional rules
  • Cross-field validation
  • Testable in isolation
Use Bean Validation for: DTOs, simple objects, standard constraints Use Fluent for: Complex business rules, conditional validation, domain objects

Q17: How do you implement cross-field validation?

Answer:
JAVA(22 lines)
Code
Loading syntax highlighter...

Q18: Fail-fast vs accumulate-all validation - trade-offs?

Answer:
Fail-fast (stop on first error):
  • ✅ Simple implementation
  • ✅ Efficient (no wasted checks)
  • ❌ Poor UX (fix one error, see next)
  • Use for: Security validation, quick checks
Accumulate-all (collect all errors):
  • ✅ Better UX (see all problems at once)
  • ✅ Fewer round trips
  • ❌ More complex code
  • ❌ May waste resources on invalid input
  • Use for: Form validation, API requests
JAVA(8 lines)
Code
Loading syntax highlighter...

Legacy Code (5 Questions)

Q19: What are characterization tests and when do you write them?

Answer: Characterization tests document the current behavior of code, not the intended behavior. They act as a safety net for refactoring.
When to write:
  • Before refactoring legacy code
  • When specification is unclear
  • When you can't afford to break existing behavior
How to write:
  1. Call the method with known input
  2. Capture actual output
  3. Assert that output (even if "wrong")
  4. Repeat for edge cases
JAVA(7 lines)
Code
Loading syntax highlighter...

Q20: Explain Strangler Fig pattern for legacy modernization.

Answer: Strangler Fig is a pattern for incrementally replacing a legacy system by growing a new system around it.
Steps:
  1. Identify a feature to replace
  2. Build new implementation alongside old
  3. Route traffic to new (start with small percentage)
  4. Gradually increase traffic to new
  5. Remove old when new is proven
  6. Repeat for next feature
Benefits:
  • No big bang rewrite
  • Can roll back if issues
  • Continuous delivery
  • Lower risk
Implementation: Feature flags, API gateway routing, database replication

Modern Java (5 Questions)

Q21: When should you use Records vs Classes?

Answer:
Use Records for:
  • Immutable data carriers (DTOs, events, value objects)
  • Simple data aggregation
  • Pattern matching targets
Use Classes for:
  • Mutable state needed
  • Complex validation in constructor
  • Non-data behavior (services, controllers)
  • Inheritance needed (records are final)
JAVA(8 lines)
Code
Loading syntax highlighter...

Q22: How do Sealed Classes enable exhaustive pattern matching?

Answer: Sealed classes restrict which classes can extend them, enabling compiler-verified exhaustive matching.
JAVA(16 lines)
Code
Loading syntax highlighter...

Spring Boot (5 Questions)

Q23: Why prefer constructor injection over field injection?

Answer:
Constructor injection:
  • ✅ Explicit dependencies (visible in signature)
  • ✅ Immutable (final fields)
  • ✅ Testable (easy to pass mocks)
  • ✅ Fails fast if dependency missing
  • ✅ No reflection needed
Field injection:
  • ❌ Hidden dependencies
  • ❌ Mutable (non-final)
  • ❌ Requires reflection or Spring for testing
  • ❌ Can create partially initialized objects
JAVA(12 lines)
Code
Loading syntax highlighter...

Q24: How do you structure packages in a Spring Boot application?

Answer:
Package by Feature (recommended):
TEXT(11 lines)
Code
Loading syntax highlighter...
Benefits:
  • Related code together
  • Easy to find everything about a feature
  • Clearer module boundaries
  • Easier to extract microservices later
Avoid Package by Layer:
TEXT
Code
Loading syntax highlighter...

Q25: What are test slices and when to use them?

Answer: Test slices load only part of Spring context for faster, focused tests.
SliceLoadsUse For
@WebMvcTestControllers, MVC configController tests (no service/repo)
@DataJpaTestJPA, repositoriesRepository tests (in-memory DB)
@JsonTestJackson configJSON serialization tests
@WebFluxTestWebFlux controllersReactive controller tests
JAVA(8 lines)
Code
Loading syntax highlighter...

🛠️ IDE Shortcuts

IntelliJ IDEA

ActionWindows/LinuxMac
Extract MethodCtrl+Alt+MCmd+Option+M
Extract VariableCtrl+Alt+VCmd+Option+V
Extract FieldCtrl+Alt+FCmd+Option+F
Extract ConstantCtrl+Alt+CCmd+Option+C
Extract ParameterCtrl+Alt+PCmd+Option+P
InlineCtrl+Alt+NCmd+Option+N
RenameShift+F6Shift+F6
Change SignatureCtrl+F6Cmd+F6
MoveF6F6
Safe DeleteAlt+DeleteCmd+Delete
Extract InterfaceCtrl+Shift+Alt+TCtrl+T → menu
Pull Up / Push DownCtrl+Shift+Alt+TCtrl+T → menu

VS Code (with Java extensions)

ActionWindows/LinuxMac
Extract MethodCtrl+Shift+RCmd+Shift+R
Extract VariableContext menuContext menu
RenameF2F2
Quick FixCtrl+.Cmd+.

Books

BookAuthorFocus
Clean CodeRobert C. MartinFundamentals of clean code
RefactoringMartin FowlerRefactoring catalog
Working Effectively with Legacy CodeMichael FeathersLegacy modernization
Effective JavaJoshua BlochJava best practices
Head First Design PatternsFreeman & RobsonPattern introduction
Design Patterns (GoF)Gamma et al.Classic pattern reference
Implementing DDDVaughn VernonDomain-Driven Design
Clean ArchitectureRobert C. MartinArchitecture patterns

Online Resources

Tools

ToolPurpose
SonarQubeCode quality metrics
JaCoCoCode coverage
PITMutation testing
SpotBugsBug detection
CheckstyleCode style
ArchUnitArchitecture tests
IntelliJ InspectionsReal-time analysis

📝 Complete Series Index

Part I: Fundamentals

  • Part 0: How to Use This Series
  • Part 1: Clean Code Philosophy & Business Value
  • Part 2: SOLID - Single Responsibility & Open/Closed
  • Part 3: SOLID - Liskov, Interface Segregation, Dependency Inversion
  • Part 4: Code Smells - Complete Catalog
  • Part 5: Code Quality Metrics Framework

Part II: Refactoring Patterns

  • Part 6: Extract Patterns (Method, Class, Interface)
  • Part 7: Replace Conditional with Polymorphism
  • Part 8: Null Handling Patterns
  • Part 9: Builder & Factory Patterns
  • Part 10: Composition Over Inheritance
  • Part 11: Functional Clean Code (Java 8-21)
  • Part 12: Chain of Responsibility & Pipeline
  • Part 13: Template Method & Hooks

Part III: Error Handling

  • Part 14: Exception Hierarchy Design
  • Part 15: Result Pattern & Functional Error Handling
  • Part 16: Global Error Handling & RFC 7807

Part IV: Validation

  • Part 17: Bean Validation & Custom Constraints
  • Part 18: Fluent Validation & Input Sanitization

Part V: Legacy Modernization

  • Part 19: Understanding Legacy Code
  • Part 20: Characterization Testing
  • Part 21: Breaking Dependencies
  • Part 22: Strangler Fig & Incremental Refactoring

Part VI: Modern Java

  • Part 23: Records, Sealed Classes & Modern Java
  • Part 24: Clean Code in Spring Boot

Part VII: Reference

  • Part 25: Decision Guide & Cheatsheet (this article)

🐛 Debug This: The Wrong Pattern

A team followed the decision tree for a switch statement but the refactoring made things worse. "We used Strategy pattern like the guide says, but now we have 15 tiny classes and the code is harder to follow!"

JAVA(46 lines)
Code
Loading syntax highlighter...
They followed the decision tree, but the result is over-engineered. What went wrong?

✅ Solution:

They followed the letter of the decision tree but missed the context questions:

Decision Tree Check:
Switch/if-else chain?
├── How many cases? → 5 cases → Consider Strategy
├── Will cases grow over time? → NO! Tax rates are configuration, not code
├── Does each case have complex logic? → NO! Just a multiplication
└── Is this behavior that needs to be injected/tested separately? → NO!
Key questions they missed:
  1. "Will cases grow over time?" - No. Tax rates are data, not behavior. If rates change, you update config, not add classes.
  2. "Is each case complex enough to warrant its own class?" - No. Each is a single line of multiplication.
  3. "YAGNI: Do you need this flexibility?" - No. They're solving a problem they don't have.
Better solution: Data-driven approach
JAVA(30 lines)
Code
Loading syntax highlighter...
When to use Strategy instead:
JAVA(20 lines)
Code
Loading syntax highlighter...
The lesson: Decision trees give guidance, not commands. Always ask: "Does this case have enough complexity and variability to justify the pattern?" Simple data lookups don't need Strategy pattern.

💻 Exercises

Exercise 1: Pattern Selection Practice

⭐ Difficulty: Easy | ⏱️ Time: 10 minutes

Task: For each code smell, use the decision trees to select the appropriate pattern.
#SmellYour Answer
1Method with 7 parametersPattern: ___ (Part: ___)
2Switch on payment type (8 cases, complex logic each)Pattern: ___ (Part: ___)
3Repeated null checks for order.getDiscount()Pattern: ___ (Part: ___)
4400-line class handling orders, payments, emailsPattern: ___ (Part: ___)
54-level deep inheritance hierarchyPattern: ___ (Part: ___)
✅ Solution:
#PatternPart
1Parameter Object or BuilderPart 6, 9
2Strategy PatternPart 7
3Null Object PatternPart 8
4Extract Class (split by responsibility)Part 6
5Composition over InheritancePart 10

Exercise 2: Refactoring Recipe Application

⭐⭐ Difficulty: Medium | ⏱️ Time: 15 minutes

Task: Apply the "Replace Conditional with Strategy" recipe to this code.
JAVA(21 lines)
Code
Loading syntax highlighter...
✅ Solution:
JAVA(60 lines)
Code
Loading syntax highlighter...

Exercise 3: Interview Question Practice

⭐⭐ Difficulty: Medium | ⏱️ Time: 20 minutes

Task: Answer these questions without looking at the answers. Then compare.
  1. What is Single Responsibility Principle and how do you identify violations?

Your answer:

TEXT(3 lines)
Code
Loading syntax highlighter...
  1. When would you use Strategy vs State pattern?

Your answer:

TEXT(3 lines)
Code
Loading syntax highlighter...
  1. How do you safely refactor a 500-line method?

Your answer:

TEXT(3 lines)
Code
Loading syntax highlighter...
After writing your answers, compare with Q1, Q7, and Q6 in the Interview Questions Bank above.

Exercise 4: Code Smell Diagnosis

⭐⭐⭐ Difficulty: Medium-Hard | ⏱️ Time: 20 minutes

Task: Identify ALL code smells in this class and map each to a refactoring.
JAVA(62 lines)
Code
Loading syntax highlighter...
Your Analysis:
SmellLocationRefactoringPart
1. ____________
2. ____________
3. ____________
............
✅ Solution:
SmellLocationRefactoringPart
Long Parameter ListprocessOrder (11 params)Extract Parameter Objects (OrderRequest, Address, PaymentInfo)Part 6
Long MethodprocessOrder (~60 lines)Extract Method (validate, checkStock, calculatePrice, processPayment, createOrder)Part 6
Field Injection@Autowired emailServiceConstructor InjectionPart 24
Raw SQL/ConnectiondbConnection.query/executeRepository PatternPart 24
Empty Catch Blockcatch (Exception e) {}Proper Exception HandlingPart 14
String Return for Errors"ERROR: ..."Result Pattern or ExceptionsPart 15
Primitive Obsessiondouble price, String cardNumberMoney, CreditCard value objectsPart 6
Feature EnvyPaymentAPI.charge in OrderManagerExtract PaymentServicePart 6
Multiple ResponsibilitiesValidation, Stock, Payment, Order, EmailExtract ServicesPart 2, 6
Magic Numbers16, 25.0, 10, 0.9Named Constants-
Static Method CallPaymentAPI.chargeInject PaymentGatewayPart 21

Exercise 5: Create Your Own Decision Tree

⭐⭐⭐⭐ Difficulty: Hard | ⏱️ Time: 25 minutes

Task: Create a decision tree for a pattern or problem you encounter frequently at work.
Template:
TEXT(15 lines)
Code
Loading syntax highlighter...
Your Decision Tree:
TEXT(9 lines)
Code
Loading syntax highlighter...
Test your tree: Apply it to 3 real examples from your codebase. Does it give the right guidance?

📅 Review Schedule for This Article

DayTaskTime
Day 1Review the Pattern Decision Trees (all 7)10 min
Day 3Redo Exercise 1 (Pattern Selection Practice)10 min
Day 7Practice answering 5 interview questions without looking15 min
Day 14Redo Debug This (The Wrong Pattern)10 min
Day 30Apply a decision tree to a real refactoring in your project20 min

🏁 Conclusion

You now have a complete reference for making clean code decisions. The key to using this guide effectively:

  1. Bookmark the decision trees - use them when facing a refactoring choice
  2. Memorize key metrics - lines > 20, parameters > 4, complexity > 10
  3. Practice the recipes - apply Extract Method, Strategy Pattern regularly
  4. Review before interviews - the 50 questions cover senior-level topics
  5. Apply incrementally - one pattern at a time, not revolutionary rewrites

Final Checklist

Before any refactoring:

  • Tests exist (or write characterization tests)
  • Identified the code smell
  • Measured the problem (metrics)
  • Selected pattern using decision tree
  • Small, reversible steps planned

During refactoring:

  • Preserve behavior (run tests after each change)
  • Commit frequently
  • Use IDE refactoring tools
  • Review for new smells introduced

After refactoring:

  • All tests pass
  • Metrics improved
  • Code review with team
  • Document decision if significant

Congratulations on completing the Advanced Clean Code Patterns series!

Remember: Clean code is not about perfection. It's about continuous improvement, pragmatic decisions, and code that your future self (and teammates) will thank you for.

Keep refactoring. Keep learning. Keep shipping.


This is the final article in the Advanced Clean Code Patterns series.