Refactoring Code in Test Driven Development (TDD)
Test Driven Development (TDD) is a software development approach where tests are written before the actual code. This process ensures that the code meets the desired functionality and encourages regular refactoring to maintain code quality.
Exam Question
The right time to refactor code using Test Driven Development is:
(choose the best answer)
A. When preparing legacy code for unit tests.
B. After the test passes.
C. After the test fails.
D. When I can see the “debt” building in the code.
Correct Answer
B. After the test passes.
Explanation
Correct Answer
B. After the test passes:
In Test Driven Development, the process typically follows three steps: Red-Green-Refactor. First, you write a failing test (Red), then you write the minimum amount of code to make the test pass (Green). Once the test passes, you enter the Refactor stage, where you clean up the code to ensure it is well-structured, maintainable, and free of unnecessary complexity. This step ensures that the code remains high-quality without changing its functionality.
Why the Other Options Are Less Appropriate
A. When preparing legacy code for unit tests:
While refactoring legacy code is important, the refactoring process in TDD specifically occurs after a test passes. Preparing legacy code for unit tests might involve some initial cleanup, but this is not the structured refactoring step as defined in TDD.
C. After the test fails:
After a test fails, the focus should be on writing the minimum amount of code required to make the test pass, not on refactoring. Refactoring occurs after the code passes the test to ensure it is as clean and efficient as possible.
D. When I can see the “debt” building in the code:
Although it’s important to address technical debt, TDD provides a specific point for refactoring, which is after the test passes. Regular refactoring as part of the TDD cycle helps prevent the accumulation of technical debt.
Relevance to the PSD Exam
Understanding when to refactor code in TDD is important for the PSD exam, as it highlights the disciplined approach of TDD in maintaining code quality throughout the development process.
Key Takeaways
- Refactoring in TDD occurs after the test passes to ensure that the code is clean and maintainable without changing its functionality.
- The Red-Green-Refactor cycle is a core principle of TDD, promoting incremental development and continuous improvement.
- Regular refactoring helps prevent technical debt and keeps the codebase healthy.
Conclusion
In Test Driven Development, the right time to refactor code is after the test passes. This ensures that the code remains clean, maintainable, and free of unnecessary complexity. For more information on preparing for the PSD exam, visit our Professional Scrum Developer PSDâ„¢ Exam Prep.