Software Engineering basics - Code refactoring

Code refactoring is the process of restructuring existing code—improving its readability, maintainability, and efficiency—without changing what the code actually does (its external behavior).

Key points about refactoring:

  • Purpose: Make the code cleaner, easier to understand, and simpler to modify in the future.

  • When: Often done when adding new features, fixing bugs, or after code reviews.

  • Techniques: Removing duplicate code, renaming variables/methods for clarity, breaking large functions into smaller ones, optimizing loops, improving file structure, etc.

  • Benefits:

    • Easier debugging and testing

    • Better performance in some cases

    • Reduces technical debt

    • Makes collaboration smoother for teams

Example:

Before refactoring:

def calc(x, y, z):
    return x*60*60 + y*60 + z

After refactoring:

def seconds(hours, minutes, seconds):
    return hours * 3600 + minutes * 60 + seconds

Both functions work the same, but the second version is clearer and easier to maintain.