DEV Community

Solomon
Solomon

Posted on Edited on AI-assisted

Write It Once, Change It Once: Reusable and Modular Code in Python

When I started learning Python, I only knew how to make code work. If it printed the right answer, I was done. Then I started building real projects, and I noticed a problem: every time I wanted to change one small thing, I had to hunt through the whole file and hope I didn’t break something else.

This article explains how I fixed that by giving every job its own function.

The problem: code that’s all mixed together

Imagine a little banking program. The code below is written in usingthe beginner way, where everything is just written out line by line:

balance = 1000

# deposit from the menu
amount = 500
if amount > 0:
    balance += amount
    print(f"Deposited {amount}")

# deposit again, this time salary
amount = 2000
if amount > 0:
    balance += amount
    print(f"Deposited {amount}")
Enter fullscreen mode Exit fullscreen mode

It works. But the deposit logic is copy-pasted. If I decide deposits need a new rule, I have to find every copy and change each one. Miss one and my program behaves differently in different places. That’s where bugs come from.

The fix: one job, one function

Put the deposit logic in one place and give it a name:

def deposit(balance, amount):
    if amount <= 0:
        print("Deposit must be positive")
        return balance
    print(f"Deposited {amount}")
    return balance + amount


def withdraw(balance, amount):
    if amount > balance:
        print("Not enough money")
        return balance
    print(f"Withdrew {amount}")
    return balance - amount


balance = 1000
balance = deposit(balance, 500)
balance = deposit(balance, 2000)
balance = withdraw(balance, 300)
print(balance)   # 3200
Enter fullscreen mode Exit fullscreen mode

Now there’s exactly one place where deposit logic lives. Anywhere I need a deposit, I call deposit()

Changing things safely

Say the bank adds a new rule: no single deposit can be bigger than 10,000. With the messy version, I’d be hunting through the file. Now I change one function and nothing else:

def deposit(balance, amount):
    if amount <= 0:
        print("Deposit must be positive")
        return balance
    if amount > 10000:
        print("Deposit too large")
        return balance
    print(f"Deposited {amount}")
    return balance + amount
Enter fullscreen mode Exit fullscreen mode

withdraw() doesn’t know or care that this happened. The rest of the program still works, and every deposit now follows the new rule automatically.

Functions can reuse each other too

Reusability isn’t only about calling the same function from many places. Functions can share smaller functions as well. Both deposit and withdraw need to check that an amount is a valid number, so I can write that check once:

def is_valid_amount(amount):
    return amount > 0


def deposit(balance, amount):
    if not is_valid_amount(amount):
        print("Amount must be positive")
        return balance
    return balance + amount


def withdraw(balance, amount):
    if not is_valid_amount(amount):
        print("Amount must be positive")
        return balance
    return balance - amount
Enter fullscreen mode Exit fullscreen mode

Now if the definition of a “valid amount” changes, I fix it in one spot and both functions get the update.

Why this made my code better

It wasn’t only about reuse. A few other things improved without my planning for them:

  1. Readability: balance = deposit(balance, 500) tells you what’s happening without reading the details.
  2. Organization: when something breaks in withdrawals, I know exactly which function to open.
  3. Easier testing: I can test deposit() by itself without running the whole program.
  4. Less fear: changing one function doesn’t feel like defusing a bomb anymore.

A few habits that helped me

  • One function, one job. If you can’t describe what it does in a short sentence, it’s probably doing too much.
  • Give functions clear names. deposit and is_valid_amount explain themselves. do_stuff doesn’t.
  • If you copy-paste code, stop. That’s usually a sign it belongs in a function.
  • Pass things in, return things out. Functions that take inputs and return results are easier to reuse than ones that depend on random variables floating around.

My final thought: You don’t need fancy Python to write reusable code. Just notice when you’re repeating yourself, and turn the repeated part into a function. Doing real projects taught me this more than any tutorial did, because that’s where you actually feel the pain of messy code.

Top comments (0)