Refactoring

Refactoring is the process of improving code structure without changing its functionality.

Elaboration:

  • Enhances readability, performance, and maintainability.
  • Common techniques:
    • Extract Method: Break a large function into smaller methods.
    • Rename Variables: Improve variable names for clarity.
    • Remove Duplications: Avoid redundant code.
  • Refactoring should be done incrementally to prevent bugs.

Example (Before & After Refactoring in Python):

Before:

python def calculate_area(length, width):
return length * width

def calculate_perimeter(length, width):
return 2 * (length + width)

After (Refactored):

class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width

def perimeter(self):
return 2 * (self.length + self.width)
  • Encapsulates related functionality inside a Rectangle class.