OCR H446, section 2.1.2 (d)
A reusable program component is a piece of code that is written once and used many times, in the same program or in different ones. Planning for reuse is part of thinking ahead.
Forms of reusable components
| Component | Description |
|---|---|
| Subroutine (function or procedure) | A named block of code called wherever it's needed |
| Module or library | A collection of related subroutines (for example math, random) |
| Class | A blueprint for objects, which can be used to create many objects, or inherited from |
| API | A defined way to use another system's features (for example a map or payment service) |
| Framework | A larger structure of ready-made components that your code plugs into |
| Template or code snippet | A reusable pattern of code |
Benefits of reuse
- Saves time and effort: you don't write the same thing again.
- Fewer errors: a component that has been tested and used many times is more reliable than new code.
- Easier maintenance: fix a bug or improve it in one place, and everything that uses it benefits.
- Shorter programs that are easier to read (less repetition).
- Consistency: the same task is done the same way everywhere.
- Teamwork: different people can build and test components separately, and use each other's.
- Lower cost and faster delivery.
Drawbacks
- A component may not quite fit the new use, and need adapting.
- Dependency: if a library is changed, withdrawn or has a security flaw, programs that use it are affected.
- Understanding someone else's code takes time, and poor documentation makes it harder.
- General components can be less efficient than ones made for a specific job.
- Licensing conditions may apply (1.5.1 (c)).
- Designing for reuse takes longer at the start: making a component general, documented and well tested is more work than writing code for one job. It pays off only if the component really is used again.
Designing components to be reusable
A component is more likely to be reusable if it:
- Does one job well (high cohesion).
- Is independent of the rest of the program (low coupling), and doesn't rely on global variables.
- Takes its data through parameters and returns results, rather than reading and printing things itself.
- Has a clear name and documented purpose, inputs, outputs and preconditions (2.1.2 (b)).
- Handles a general case, not just one specific value.
- Has been tested, including awkward cases.
Not reusable
def show_total():
# only works for this one list, and prints directly
print(sum(prices) * 1.2)
Reusable
def total_with_vat(prices, rate=0.2):
"""Return the total of prices with VAT added."""
return sum(prices) * (1 + rate)
print(total_with_vat([10, 20, 5]))
print(total_with_vat([100], 0.05))
The second version works for any list and any rate, and returns a value that can be printed, stored or used in other calculations.
Reuse by object-oriented programming
- A class can be used to create many objects.
- Inheritance lets a new class reuse the attributes and methods of an existing one, and add or change only what's different:
class Account:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
class SavingsAccount(Account): # reuses deposit()
def add_interest(self, rate):
self.balance *= 1 + rate
Worked example
Task: a programmer needs to check whether a password is strong in the sign-up page, the change-password page and the admin tool. Explain how reusable components help.
- Write one function
is_strong(password)that returnsTrueorFalse, and keep it in a module that all three parts import. - Benefits: the rules are written once. If the rules change (for example a minimum length of 12), it is changed in one place and all three pages are updated. It is tested once, so all three are reliable, and all three behave consistently.
- Why it's reusable: it takes the password as a parameter, returns a result, and does no input or output of its own.
def is_strong(password):
return (len(password) >= 8
and any(c.isdigit() for c in password)
and any(c.isupper() for c in password))
Exam tip: give specific benefits (saves time, already tested so more reliable, one place to fix) and mention how components are made reusable (parameters, no global variables, one clear job, documentation). A good answer includes a drawback such as dependency or fit.
Check yourself
Give three benefits of reusable components
Any three of: saves development time; already tested so more reliable; easier to maintain because a fix is made in one place; shorter, more readable code; consistency.
Give two examples of reusable components
Any two of: a subroutine, a library or module, a class, an API, a framework.
Why should a reusable subroutine use parameters and return values instead of global variables?
It then doesn't depend on the rest of the program, so it can be used in different places with different data without being changed.
Give one disadvantage of reusing existing components
It may not fit exactly and need adapting; the program depends on code that might change or be withdrawn; poor documentation can make it hard to use; licence conditions may apply.