Module 3 Lesson 6: Writing Reusable Code
·Programming

Module 3 Lesson 6: Writing Reusable Code

Going from 'it works' to 'it's good.' Learn the best practices for writing functions that are reusable, testable, and clean.

Module 3 Lesson 6: Writing Reusable Code

A junior developer writes code that "works." A senior developer writes code that can be easily understood and reused by others. In this lesson, we will cover the principles of Reusable Code—how to turn your scripts into professional-grade libraries.

Lesson Overview

In this lesson, we will cover:

  • Single Responsibility Principle: One function, one job.
  • Pure Functions: Predictable inputs and outputs.
  • The Power of Docstrings: Documenting your code correctly.
  • Avoid "Hard-coding": Using arguments instead of constants.

1. One Function, One Job

A common mistake is making a "God Function" that does everything: gets input, calculates math, saves data, and prints results.

Better Approach: Break it down.

  • get_user_data()
  • calculate_tax()
  • print_report()

If your function name has the word "and" in it (e.g., calculate_and_print), it probably needs to be split!


2. Pure Functions (Predictability)

A "Pure Function" is a function that:

  1. Always gives the same output for the same input.
  2. Does not change any global variables (no "side effects").

Pure functions are easy to test and less likely to cause weird, untraceable bugs in large programs.


3. The Power of Docstrings

A docstring is a multi-line comment at the start of a function that explains what it does, what it takes, and what it returns.

def calculate_bmi(weight_kg, height_m):
    """
    Calculates the Body Mass Index.
    
    Args:
        weight_kg (float): Weight in kilograms.
        height_m (float): Height in meters.
        
    Returns:
        float: The calculated BMI value.
    """
    return weight_kg / (height_m ** 2)

Why do this? Other programmers—and the AI tools you use (like VS Code)—can see this documentation instantly as they type!


4. Don't "Hard-code" Values

Instead of writing a function that always calculates a 15% tip, write a function that takes the tip percentage as an argument (with a default of 15).

# HARD-CODED (Bad)
def calc_tip(bill):
    return bill * 0.15

# REUSABLE (Good)
def calc_tip(bill, percent=15):
    return bill * (percent / 100)

Practice Exercise: The Refactor Challenge

Copy this clunky code and refactor it into three separate, reusable functions with proper docstrings:

# CLUNKY CODE
def do_everything():
    name = input("Name: ")
    price = float(input("Price: $"))
    tax = price * 0.1
    total = price + tax
    print(f"Receipt for {name}: ${total}")

do_everything()

Quick Knowledge Check

  1. What is the "Single Responsibility Principle"?
  2. What is a "Pure Function"?
  3. How do you start and end a docstring in Python?
  4. Why is "hard-coding" values inside a function a bad idea?

Key Takeaways

  • Keep functions small and focused on one task.
  • Document your functions using """docstrings""".
  • Avoid side effects (changing globals) whenever possible.
  • Use parameters to make logic flexible and reusable.

What’s Next?

We’ve learned how to write great functions. But how do we organize them into different files and use them in other projects? In Lesson 7, we’ll explore Importing Modules!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn