CodingNic

Testing and Best Practices

Refactoring Basics

Testing and Best Practices 34 min read

Refactoring Basics

Refactoring Basics

Sometimes code works, but the code is messy.

It may be hard to read, repeated, or difficult to maintain.

Improving code structure without changing behavior is called refactoring.

What Is Refactoring?

Refactoring means cleaning and improving code while keeping the same output.

The program should still do the same job.

Why Refactor?

Refactoring helps you:

  • reduce repetition
  • improve readability
  • make debugging easier
  • simplify updates
  • organize code better

Important Rule

Refactor in small steps and run tests after changes.

Example: Repeated Code

Before:

python
name1 = "Tom"
print("Hello", name1)

name2 = "Sara"
print("Hello", name2)

This repeats the same idea.

Better: Use a Function

python
def greet(name):
    print("Hello", name)

greet("Tom")
greet("Sara")

Example: Bad Variable Names

Before:

python
a = 10
b = 5
c = a * b
print(c)

Better:

python
price = 10
quantity = 5
total = price * quantity

print(total)

Example: Long Function

Before:

python
def process():
    print("Login")
    print("Load Data")
    print("Show Report")

Better:

python
def login():
    print("Login")

def load_data():
    print("Load Data")

def show_report():
    print("Show Report")

def process():
    login()
    load_data()
    show_report()

Why This Is Better

Small functions are easier to test and reuse.

Refactoring Checklist

Ask:

  • Is code repeated?
  • Are names clear?
  • Is one function too large?
  • Can logic be simplified?
  • Do tests still pass?

Code Along

Take a small program with repeated prints.

Refactor it into a function.

Mini Challenge

Refactor this code:

python
def calc():
    x = 2
    y = 3
    print(x + y)

Tasks:

  • Use clearer names
  • Return the result instead of printing
  • Rename the function

Expected improved version:

python
def add_numbers():
    first = 2
    second = 3
    return first + second

Real World Use Case

Developers refactor apps regularly to keep code clean as features grow.

Quiz

  1. What is refactoring?
  2. Should behavior change during refactoring?
  3. Why run tests after refactoring?
  4. Name one sign code needs refactoring.

Assignment

Choose one old project and improve names, functions, or repeated code without changing output.

Summary

You learned how refactoring improves code structure while keeping the same behavior.