UPI Study › Courses › Software Engineering › Free lessons › Lesson 4.6 Free with a free account
Refactoring in Agile: Cleaning Code Without Breaking It
Software Engineering · Chapter 4: Rapid Development, Testing, and Software EvolutionSection 4.6 · lesson 29 of 1037 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Software Engineering.
Lesson complete
Earn the 3 college credits for Software Engineering
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Getting Started with Agile Thinking →← How Software Changes Over Time: Evolution and MaintenanceNext lesson: Getting Started with Agile Thinking →
In this lesson
Code smells, common techniques, and the tests that make it safe.
- Define refactoring, and distinguish it from fixing bugs or adding features
- Recognize common code smells, and the techniques that address them
- Explain refactoring's role in agile and Extreme Programming
- Explain why an automated test suite makes refactoring safe
Transcript
Everything said in the video, section by section (1,035 words). Read along, or search it.
Rapid Development, Testing, and Software Evolution
Refactoring in Agile: Cleaning Code Without Breaking It
Is it possible to genuinely improve code that already works, without any risk of quietly breaking it? That is the promise of refactoring. This section covers what refactoring is, the signals that prompt it, the common techniques, and the tests that make it safe.
The Question
Improving Code That Already Works
Refactoring is the practice of restructuring existing code, to make it clearer, simpler, or easier to work with. And it does that without changing what the code actually does. A user running the software before and after a refactoring should not be able to tell the difference. The outward behavior is identical. What changes is the internal structure. How the code is organized, how it is named, and how it is broken into pieces.
What It Isn't
3 Activities, 1 Difference
That separates refactoring from two activities it is often confused with. Fixing a bug changes behavior on purpose, because the existing behavior was wrong. Adding a feature also changes behavior on purpose, because new behavior is wanted. Refactoring changes neither. Its entire goal is to leave behavior exactly as it was, while making the code easier to read, understand, and extend later.
Table 1
Code Smells
Developers rarely refactor at random. It is usually triggered by noticing a code smell. A code smell is a pattern that is not necessarily wrong, but tends to signal a deeper problem worth a closer look. Duplicated code is the same, or very similar, code in more than one place. A long method has grown to do far more than one clear thing. A large class has taken on so much that it is hard to summarize. A long parameter list makes a method hard to call correctly. And feature envy is a method more interested in another object's data than its own. Remember, a smell is a symptom, not a diagnosis. It only means it is worth asking whether a clearer structure is available.
Table 2
Common Refactoring Techniques
Once a smell is noticed, a small set of well-known techniques covers most of what refactoring involves. Extract method pulls a block of code out of a larger method, into its own, clearly named method. Rename replaces an unclear name with one that describes what the code actually represents, or does. Extract class splits a class that has taken on too many responsibilities into two more focused classes. And replacing a magic number with a constant gives an unexplained literal value a descriptive name.
Extract Method, Applied
Same Total, Clearer Code
Here is extract method in action. Before, the print invoice method does two jobs. It loops over the order's items to add up the total, and then it prints that total. After, the loop has moved into its own method, called calculate total. Print invoice simply calls it, and prints the result. Notice what did not change. Calling print invoice still prints exactly the same total as before. What changed is that the total now comes from a method whose name says exactly what it does. That makes it easier to read, and to reuse elsewhere.
Agile and XP
Continuous, Not a Cleanup Phase
In agile development, and particularly in Extreme Programming, or X P, refactoring is not a separate cleanup phase scheduled for later. It is done continuously, in small steps, as a normal part of every iteration. That fits the way agile teams build software. Requirements are expected to change, and features are added incrementally. So the code's structure has to keep adapting along with them. Code that was well organized for the first few increments can become awkward, once several more have been added on top. Continuous refactoring keeps the code comfortable to extend, rather than letting that awkwardness pile up into a serious obstacle.
Think About It
Why Spend the Time?
Here is a question to think about. If refactoring never changes behavior, why does it matter enough to spend time on in every iteration? Because code that is hard to read is also hard to change safely. Time spent keeping code clear now is time saved, every time a future increment has to build on top of it.
The Safety Net
How Do You Know Nothing Changed?
Restructuring code without changing its behavior sounds simple. But how would anyone actually confirm that the behavior really stayed the same? That is exactly the problem an automated test suite solves. A thorough set of tests, run before and after a refactoring, tells the developer directly whether the code still behaves the way it did. Without that safety net, refactoring is just a guess.
Figure 2
The Test-Protected Cycle
Here is the cycle that keeps refactoring safe. First, confirm that all the tests pass, before touching anything. Then make one small change. And then run the tests again. If the tests stay green, keep going, and start the loop again with the next small change. If the tests fail, revert that change.
Why Small Steps
Keeping Every Failure Traceable
The cycle is deliberately small, for a reason. Because the tests passed before you started, any failure afterward can be traced to the specific change you just made, not some earlier, unrelated edit. And if the tests fail, the safest response is usually to revert that one small change, rather than trying to debug forward from an unclear state. It is also why refactoring without a solid test suite is much riskier. Without tests, there is no reliable way to know behavior stayed the same.
Key Terms
The Vocabulary of This Section
Let's lock in the key terms. Refactoring is restructuring existing code to make it clearer or simpler, while leaving its external behavior unchanged. A code smell is a pattern that is not necessarily incorrect, but often signals a deeper problem worth investigating. Extract method is a technique that pulls a block of code out of a larger method, into its own, clearly named method. And a test suite is a collected set of automated tests, used to confirm that code behaves as expected, including after a refactoring.
Key Takeaways
What to Carry Forward
To pull this together. Refactoring restructures code to make it clearer or simpler, without changing its behavior, unlike fixing a bug or adding a feature. Code smells like duplicated code, long methods, and large classes are signals worth investigating, not proof that something is broken. Techniques like extract method, rename, extract class, and named constants cover much of the practice. In agile and X P, refactoring happens continuously, in small steps, rather than as a separate cleanup phase. And an automated test suite is the safety net that makes it possible. Without it, restructuring code is a risky guess.
About Software Engineering at UPI Study
Software Engineering (Computer Science 301) is a self-paced online course of 103 video lessons in 15 chapters, from process models and agile to requirements, design, user interfaces, reliability, security and project management. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Why take it here
Why students take Software Engineering with UPI Study
Where the credit goes
Universities that work with NCCRS
Software Engineering carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Refactoring in Agile: Cleaning Code Without Breaking It
What is refactoring in software development?
What is a code smell?
What is the extract method refactoring technique?
Why do you need automated tests before refactoring?
About the Software Engineering course
How many college credits is Software Engineering?
How much does Software Engineering cost and what is included?
Which universities accept UPI Study credits?
How long does Software Engineering take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Software Engineering.
103 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →