⬅ Previous Topic
Version Control BasicsNext Topic ⮕
Testing and Code Reviews⬅ Previous Topic
Version Control BasicsNext Topic ⮕
Testing and Code ReviewsModular code refers to the practice of breaking down a program into independent, self-contained units or "modules." Each module handles a specific part of the program’s functionality and can be reused across different projects.
Let’s say we are building a program to manage users and calculate taxes.
START
name = input("Enter user name")
income = input("Enter annual income")
if income > 50000 THEN
tax = income * 0.2
ELSE
tax = income * 0.1
ENDIF
print("User:", name)
print("Tax:", tax)
END
This works for a small program, but what if we need to calculate tax in multiple places or change tax rules?
We separate logic into functions and group related tasks.
FUNCTION getUserInput
name = input("Enter user name")
income = input("Enter annual income")
RETURN (name, income)
END
FUNCTION calculateTax(income)
IF income > 50000 THEN
RETURN income * 0.2
ELSE
RETURN income * 0.1
ENDIF
END
FUNCTION printUserTax(name, tax)
print("User:", name)
print("Tax:", tax)
END
START
(name, income) = getUserInput()
tax = calculateTax(income)
printUserTax(name, tax)
END
Enter user name: Alice Enter annual income: 60000 User: Alice Tax: 12000.0
What if we had to change tax rates? How would modular code help?
Instead of editing every tax calculation in the program, we only update the calculateTax
function—saving time and reducing error.
As projects grow, organize code into folders and files:
project-root/
│
├── main.pseudo
├── user/
│ ├── input.pseudo
│ └── display.pseudo
├── tax/
│ └── calculator.pseudo
└── utils/
└── logger.pseudo
In your main file, import and use only what’s needed:
IMPORT getUserInput FROM user/input
IMPORT calculateTax FROM tax/calculator
IMPORT printUserTax FROM user/display
START
(name, income) = getUserInput()
tax = calculateTax(income)
printUserTax(name, tax)
END
Q: Which of the following is a benefit of modular programming?
Answer: D. All of the above
⬅ Previous Topic
Version Control BasicsNext Topic ⮕
Testing and Code ReviewsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.