Menu

Abstraction and Decomposition

Subprograms

A subprogram is a named block of code that performs one specific task and can be called from other parts of a program. You write it once, give it a name, and call it whenever that task is needed.

Building a program from parts

Using subprograms is one way decomposition appears in code: the overall job is split into smaller tasks, and each task becomes its own subprogram. The main program then reads as a short list of calls, plus any logic that does not belong in a subprogram. Plenty of what a real program does — working out a price, checking a password, drawing a shape — happens inside subprograms.

Why reuse matters

Because a subprogram can be called many times, the same code never needs copying and pasting. That cuts development time and reduces errors, since there is only one version to get right. If the task changes, you edit the subprogram once and every call uses the new version. That makes the program easier to maintain, and easier to adapt because one task can be updated without rewriting the whole program. Separate programmers can also write different subprograms and join them together.

The call is an abstraction

A call hides the internal logic: you only need the subprogram's name, the values it needs and what it gives back. That is abstraction, and it happens whether or not the name is descriptive — the call hides the code, not the name. Built-in and library subprograms such as len() and print() work the same way: you use them without knowing how they are written inside.

In this booking program, one subprogram works out the cost of one booking line. It is called once for climbing and once for kayaking, so the multiplication is written once but used twice, and the main program just adds the results together.

def line_total(quantity, unit_price):
    # cost of one line of the booking
    return quantity * unit_price

climbing = line_total(4, 12.50)
kayaking = line_total(2, 18.00)
print("Climbing: " + str(climbing))
print("Kayaking: " + str(kayaking))
print("Total: " + str(climbing + kayaking))

Output:

Climbing: 50.0
Kayaking: 36.0
Total: 86.0

Practise this