Tutorials Home   >   Software Development Basics   >   Refactoring Basics

Refactoring Basics

1. Introduction

Refactoring is the process of improving the internal structure of code without changing its external behavior.

In simple words:

β€œMaking your code cleaner, simpler, and easier to maintain, while keeping it functional.”

Refactoring is not about fixing bugs or adding new features. It’s about making the existing code better.


2. Why Refactoring is Important

  1. Improves readability – Easier for you or others to understand the code.

  2. Simplifies maintenance – Easier to modify or extend in the future.

  3. Reduces technical debt – Avoids messy code accumulating over time.

  4. Helps in finding hidden bugs – Cleaner code can reveal mistakes.

  5. Encourages reuse – Functions and modules can be reused effectively.


3. When to Refactor

  • After writing a working piece of code.

  • Before adding new features.

  • When code is messy or duplicated.

  • During code review.

  • When performance can be improved without changing functionality.

Rule of thumb: Refactor small parts frequently, not the entire program at once.


4. Principles of Refactoring

  1. Keep Behavior the Same

    • Refactoring should not change what the code does.

    • Always test before and after refactoring.

  2. Small Steps

    • Make one change at a time.

    • This reduces risk of introducing errors.

  3. Continuous Testing

    • Test after each change to ensure the program still works.

  4. Readable and Simple Code

    • Break large functions into smaller ones.

    • Remove redundant code.


5. Common Refactoring Techniques

a) Renaming Variables and Functions

  • Use meaningful names instead of short, unclear ones.

// Before
int t;
t = calculate(x, y);
// After
int totalMarks;
totalMarks = calculateTotalMarks(studentScore, bonusPoints);


b) Extracting Functions

  • Break large functions into smaller functions with single responsibility.

// Before
void processStudent() {
// Input student data
// Calculate marks
// Print results
}
// After
void inputStudentData() { }
void calculateMarks() { }
void printResults() { }

void processStudent() {
inputStudentData();
calculateMarks();
printResults();
}


c) Removing Duplicate Code

  • If the same code is repeated, put it in a function.

// Before
printf("Hello, John\n");
printf("Hello, Mary\n");
// After
void greet(char *name) {
printf(“Hello, %s\n”, name);
}

greet(“John”);
greet(“Mary”);


d) Simplifying Conditionals

  • Replace complex if-else chains with simpler logic.

// Before
if(status == 1){
printf("Active");
}else if(status == 2){
printf("Inactive");
}else{
printf("Unknown");
}
// After
switch(status){
case 1: printf(“Active”); break;
case 2: printf(“Inactive”); break;
default: printf(“Unknown”);
}


e) Removing Magic Numbers

  • Replace numbers with named constants.

// Before
for(int i=0; i<50; i++) { }
// After
#define MAX_STUDENTS 50
for(int i=0; i<MAX_STUDENTS; i++) { }


f) Consolidating Duplicate Conditions

  • Combine repeated conditions to make code concise.

// Before
if(x>0 && y>0){ ... }
if(x>0 && y>0 && z>0){ ... }
// After
bool positiveXY = x>0 && y>0;
if(positiveXY){ … }
if(positiveXY && z>0){ … }


g) Comment Cleanup

  • Remove unnecessary comments.

  • Keep useful comments that explain the logic.


6. Benefits of Refactoring

  • Readable code – Easy to understand.

  • Maintainable code – Easy to modify and extend.

  • Reduced bugs – Cleaner logic means fewer mistakes.

  • Reusable code – Functions and modules can be reused.

  • Better performance – Simplified logic may improve efficiency.


7. Refactoring Checklist

Task Action
Naming Use descriptive names for variables, functions, and constants
Function size Keep functions short and focused on a single task
Duplicate code Remove repeated code using functions
Magic numbers Replace with named constants
Conditionals Simplify nested or complex if-else statements
Comments Keep only meaningful comments
Testing Test code before and after each refactoring step

8. Example: Refactoring a Small Program

Original Code (Unrefactored)

#include <stdio.h>
int main() {
int t=0;
for(int i=0;i<10;i++){
if(i%2==0){
t+=i;
}
}
printf("%d",t);
return 0;
}

Refactored Code

#include <stdio.h>

int sumEvenNumbers(int n) {
int sum = 0;
for(int i = 0; i < n; i++) {
if(i % 2 == 0) {
sum += i;
}
}
return sum;
}

int main() {
int total = sumEvenNumbers(10);
printf(“Sum of even numbers: %d”, total);
return 0;
}

  • Notice the improvements:

    • Function extracted

    • Meaningful variable names

    • Readable formatting


9. Conclusion

Refactoring is an essential skill for professional programmers.
By refactoring:

  • You make code cleaner, readable, and maintainable

  • Reduce technical debt and bugs

  • Improve collaboration in teams

  • Ensure your code is ready for future changes

Remember: Refactoring doesn’t add new features; it makes your existing code better.