1.1.2 Benefits of subprograms
What Is a Subprogram?
A subprogram is a named block of code that performs a specific task and can be called from elsewhere in a program. Subprograms are the building blocks of structured programming. There are two types:
| Type | Definition | Returns a value? | PLS syntax |
|---|---|---|---|
| Procedure | Performs a task but does not return a value to the calling code | No | def name(): |
| Function | Performs a task and returns a value to the calling code | Yes | def name(): ... return value |
# Procedure — does a task, returns nothing
def display_welcome():
print("Welcome to the quiz!")
# Function — calculates and returns a result
def calculate_area(length, width):
area = length * width
return area
Benefits of Using Subprograms
A subprogram is written once but can be called many times from anywhere in the program. This avoids duplicating the same code in multiple places — a principle known as DRY (Don't Repeat Yourself). If the logic needs to change, it is updated in one place only.
# Written once, called multiple times
def validate_age(age):
return age >= 0 and age <= 120
# Used in different parts of the program
if validate_age(student_age):
print("Valid")
if validate_age(staff_age):
print("Valid")
A subprogram can be tested in isolation with known inputs and expected outputs before the full program is complete. This makes finding and fixing bugs much easier — if the subprogram passes its tests, it can be trusted when called from elsewhere.
Testing small units of code individually is called unit testing and is a cornerstone of professional software development.
Using well-named subprograms makes a program easier to read and understand. Instead of a long block of code, the main program reads like a series of clear instructions:
display_welcome()
load_questions()
run_quiz()
display_final_score()
A reader can understand the overall flow without needing to know the internal details of each subprogram. Subprograms also make programs easier to maintain — a change to one task only affects that subprogram.
In a team project, different programmers can work on different subprograms simultaneously. Once the interface (name, parameters, return value) of each subprogram is agreed, each team member works independently without needing to understand the rest of the system.
Subprograms can also be collected into libraries — collections of reusable code shared across multiple projects, saving significant development time.
Key Takeaways
- A procedure performs a task and does not return a value; a function performs a task and returns a value.
- Subprograms improve reusability — write once, call many times.
- Subprograms improve testability — each can be tested in isolation.
- Subprograms improve readability and maintainability — clear structure, changes in one place.
- Subprograms enable team development — different programmers work on different subprograms simultaneously.