Chapter 3: Chapter 3. Refactoring in small steps
The introduction frames a template-engine design problem and defines a spike as throwaway prototyping used to explore a potential solution.
After this chapter you will be able to
- Spike solution purpose. Explain what a spike is and what it helps developers learn about a potential solution.
- Spike as solution exploration. Explain what a spike is and describe ways to explore a potential solution to the double-rendering problem.
- Purpose of a spike. Explain what a spike is and how it helps evaluate a potential solution.
- Spike and production code. Describe how test-first discipline can differ during a spike and how its results should be used in production development.
- Learning tests for API exploration. Explain what learning tests are and how they help explore whether an API can support a potential solution.
- Template segmentation solution. Explain the proposed template segmentation approach and why it avoids interpreting a rendered variable value as another variable.
- Learning Through Spike Experiments. Explain how the learning tests exposed an incorrect API assumption and what the spike produced.
- Groups Versus Pattern Occurrences. Distinguish Matcher groupCount from the number of pattern occurrences, and explain what removing parentheses showed in the example.
- Finding Successive Match Positions. Explain how repeated find calls and the start and end methods locate matches, and why those positions help parse a template.
- Case-by-case development strategy. Explain why the example moves from faking template parsing toward a depth-first approach.
- Independent parser test progression. Trace how the new TemplateParse class is developed from the simplest tests through a test containing a variable.
- Template segmentation algorithm. Trace how the parser uses placeholder matches to collect plain-text and variable segments, including the remaining tail and empty input.
- Implementation step size. Explain the reflection on separating parsing logic while taking too large a step to implement it.
- Tested parser switchover. Explain how the existing parsing logic is replaced without intentionally changing functionality, and how the tests support the change.
- Parsed segment rendering. Trace how evaluate uses TemplateParse and renders variable and plain-text segments.
- Segment representation design smells. Explain the remaining smells in append and the proposed direction for addressing them.
- Uniform segment handling. Explain how the proposed Segment interface would let Template treat segments alike and what the parser and segments must provide.
- Small-step refactoring sequence. Describe why the section temporarily undoes the evaluate changes and what it proposes doing before returning to Template.
- Temporary parsing compatibility. Explain how the new Segment-based parser is introduced without breaking existing callers.
- Reuse of existing parsing. Trace how parseSegments builds on existing parsing and how the shared variable check is made available.
- Polymorphic segment evaluation. Explain how Segment implementations take on rendering behavior and how variable segments use the supplied values.
- Segment based switchover. Describe the change to Template.evaluate and why it is straightforward at this point.
- Missing variable regression. Explain how the tests catch the missing-variable regression and how the section restores the behavior.
- Post switchover cleanup. Describe the cleanup made after the switchover and distinguish it from the further refactoring left as an exercise.
What it builds on
- A looming design dead-end (chapter 2) · The existing template design problem exposed by a test.
- Faking details a little longer (chapter 2) · The earlier decision to keep faking parsing details.
- Writing the first failing test (chapter 2) · Starting with a failing test
- Making the first test pass (chapter 2) · Making a test pass with a simple implementation
- Potential refactorings in test code (chapter 2) · Recognizing opportunities to refactor test code
- Developing in small increments (chapter 1) · Developing in small increments
- Programming by intention (chapter 2) · Programming by intention designs the desired behavior from the caller’s perspective.
- Expecting an exception (chapter 2) · The existing expectation that an error raises an exception.
Section by section
Introduction
The introduction frames a template-engine design problem and defines a spike as throwaway prototyping used to explore a potential solution.
- Spike solution purpose: Explain what a spike is and what it helps developers learn about a potential solution.
Why it matters: A spike lets you investigate an uncertain solution before committing to it.
Key terms: spike solution, spike, throwaway prototyping
3.1 Exploring a potential solution
This section introduces a spike as exploratory work to evaluate or find an approach to a problem.
- Spike as solution exploration: Explain what a spike is and describe ways to explore a potential solution to the double-rendering problem.
Why it matters: A spike gives you a way to investigate an uncertain solution before committing to an approach.
Key terms: spike, Extreme Programming, exploratory process
3.1.1 Prototyping with spikes
This section explains how spikes reduce uncertainty about potential solutions and how to use their findings without compromising production code.
- Purpose of a spike: Explain what a spike is and how it helps evaluate a potential solution.
Why it matters: A spike gives you a focused way to reduce uncertainty before committing to a solution. - Spike and production code: Describe how test-first discipline can differ during a spike and how its results should be used in production development.
Why it matters: Separating experimental code from production work helps keep the software healthy.
Key terms: spike, experiment, test-first, production code
3.1.2 Learning by writing tests
The section introduces learning tests for exploring an API and proposes segmenting templates to prevent variable values from being interpreted as variables.
- Learning tests for API exploration: Explain what learning tests are and how they help explore whether an API can support a potential solution.
Why it matters: Learning tests let you investigate an API through concrete, executable examples. - Template segmentation solution: Explain the proposed template segmentation approach and why it avoids interpreting a rendered variable value as another variable.
Why it matters: This proposed design addresses the failing template case without treating substituted values as template variables.
Key terms: learning tests, automated tests, spikes, plain-text segments, variable segments, parse, evaluate
3.1.3 Example spike for learning an API
A learning-test spike explores Java’s Matcher API and discovers how to locate template placeholders without relying on match groups.
- Learning Through Spike Experiments: Explain how the learning tests exposed an incorrect API assumption and what the spike produced.
Why it matters: Small experiments can reveal a mistaken assumption before it shapes an implementation. - Groups Versus Pattern Occurrences: Distinguish Matcher groupCount from the number of pattern occurrences, and explain what removing parentheses showed in the example.
Why it matters: Distinguishing groups from occurrences prevents choosing the wrong API for finding placeholders. - Finding Successive Match Positions: Explain how repeated find calls and the start and end methods locate matches, and why those positions help parse a template.
Why it matters: Match positions provide the information needed to separate placeholders from surrounding template text.
Key terms: spike, learning tests, groupCount, match groups, regular expression, find, start, end, variable placeholders, plain text segments
3.2 Changing design in a controlled manner
The section explains a case-by-case choice of development approach and checks the test baseline before refactoring.
- Case-by-case development strategy: Explain why the example moves from faking template parsing toward a depth-first approach.
Why it matters: The example shows how the state of the code can influence the route toward a complete solution. - Pre-refactoring test baseline: Describe the test check before refactoring and the limitation of the passing result.
Why it matters: A passing baseline is useful to interpret in light of any test that has been temporarily excluded.
Key terms: breadth-first, depth-first, faking, Template, tests, double-rendering problem
3.2.1 Creating an alternative implementation
The section test-drives a separate template parser, refactors its tests, and reflects on the size and complexity of the implementation step.
- Independent parser test progression: Trace how the new TemplateParse class is developed from the simplest tests through a test containing a variable.
Why it matters: Starting with simple tests makes a new implementation manageable before tackling variable parsing. - Test duplication and intent: Describe how the parser tests are refactored to remove duplication and make assertions communicate their intent.
Why it matters: Clear, nonduplicated tests are easier to maintain while continuing to check the parser. - Template segmentation algorithm: Trace how the parser uses placeholder matches to collect plain-text and variable segments, including the remaining tail and empty input.
Why it matters: The segmentation algorithm is the working alternative that will later be connected to the template engine. - Implementation step size: Explain the reflection on separating parsing logic while taking too large a step to implement it.
Why it matters: Even with tests as a safety net, a large implementation leap can make progress harder to control.
Key terms: TemplateParse, plain text segment, failing test, helper method, varargs, custom assertion methods, collectSegments, variable placeholder, plain-text segments, variable segments
3.2.2 Switching over safely
The section switches template parsing to TemplateParse under test, then refactors the rendering code and identifies remaining design smells.
- Tested parser switchover: Explain how the existing parsing logic is replaced without intentionally changing functionality, and how the tests support the change.
Why it matters: Tests help you change an implementation while checking that its existing behavior still works. - Parsed segment rendering: Trace how evaluate uses TemplateParse and renders variable and plain-text segments.
Why it matters: This explains how the replacement parser fits into the existing template evaluation. - Method extraction for clarity: Describe the extractions used to make evaluate and append easier to read.
Why it matters: Small extractions make the code’s purpose clearer without requiring a functional change. - Segment representation design smells: Explain the remaining smells in append and the proposed direction for addressing them.
Why it matters: Recognizing the remaining smells gives the next design change a clear purpose.
Key terms: TemplateParse, refactor, green bar, evaluate, segments, StringBuilder, variables map, level of abstraction, rendering logic, extracting methods
3.3 Taking the new design further
The section designs a uniform Segment interface and plans a small-step refactoring toward it.
- Uniform segment handling: Explain how the proposed Segment interface would let Template treat segments alike and what the parser and segments must provide.
Why it matters: A common segment interface makes the template code independent of segment-specific branching. - Small-step refactoring sequence: Describe why the section temporarily undoes the evaluate changes and what it proposes doing before returning to Template.
Why it matters: Sequencing the change in smaller steps helps keep the refactoring manageable.
Key terms: Segment, TemplateParse, StringBuilder, Map, programming by intention, evaluate, test first, small steps
3.3.1 Keeping things compatible
The section introduces Segment-based parsing and evaluation alongside the existing implementation, preparing for a compatible switchover.
- Temporary parsing compatibility: Explain how the new Segment-based parser is introduced without breaking existing callers.
Why it matters: Keeping both paths temporarily lets the design change proceed without breaking existing tests. - Reuse of existing parsing: Trace how parseSegments builds on existing parsing and how the shared variable check is made available.
Why it matters: Building on working parsing logic keeps the new implementation small while tests check the enabling change. - Polymorphic segment evaluation: Explain how Segment implementations take on rendering behavior and how variable segments use the supplied values.
Why it matters: Putting varying rendering behavior in segment objects prepares the design to replace conditional logic. - Equality and hashCode contract: Describe the limitation of the initial Segment equality implementations and the section's test-first response.
Why it matters: The example distinguishes passing current tests from fulfilling the broader equals and hashCode contract.
Key terms: parseSegments, parse, backward compatibility, isVariable, Template, TemplateParse, Segment, evaluate, polymorphism, Variable
3.3.2 Making the switchover
The section switches Template to the new segment-based design, uses tests to catch a behavioral regression, and cleans up obsolete code.
- Segment based switchover: Describe the change to Template.evaluate and why it is straightforward at this point.
Why it matters: Preparing the new objects first makes the eventual switchover a small change. - Missing variable regression: Explain how the tests catch the missing-variable regression and how the section restores the behavior.
Why it matters: The tests protect existing behavior while the implementation changes. - Post switchover cleanup: Describe the cleanup made after the switchover and distinguish it from the further refactoring left as an exercise.
Why it matters: Removing obsolete code and narrowing access clarify responsibilities after a design change.
Key terms: Template, evaluate, TemplateParse, Segment, test suite, missing variable values, Variable, exception, dead code, isVariable
3.4 Summary
Concepts explained in this chapter
- code spikeA spike solution is an exploratory prototype used to investigate a potential solution and estimate its feasibility or effort.
- refactoringA disciplined technique for changing a program's internal structure without changing its observable behavior.
- polymorphismPolymorphism is the object-oriented capability for objects of different types to provide type-specific behavior through a shared interface.
- learning testA learning test is an automated test that verifies assumptions about code and teaches how that code behaves.
- abstraction levelAn abstraction level is the degree of conceptual detail at which a method or other program element expresses its work.
- test-driven developmentTest-driven development is a software development technique in which tests are written before the code they guide and verify.
- acceptance test-driven developmentAcceptance test-driven development is a practice in which acceptance tests guide implementation of system behavior.
- code duplicationCode duplication is the repetition of the same or similar code in multiple places in a software system.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
