B2.3.4 · Programming constructs
Functions and modularization
By the end you can
Design modular functions and procedures, contrasting pass-by-value and pass-by-reference parameter passing.
decomposes a large software program into discrete, manageable subroutines. Modularization eliminates code duplication, facilitates unit testing, enables code reuse, and allows development teams to collaborate simultaneously on separate modules.
Functions vs procedures#
- Functions: Subroutines that compute and return a value using a
returnstatement. They can be used inline within expressions (e.g.y = Math.sqrt(x) + 5). - Procedures: Subroutines executed for their side effects (such as printing output, updating a database, or rendering a UI element) without returning a value (declared with
voidin Java/C++).
Parameters: Value vs Reference#
Parameters allow data to be passed into subroutines:
- Pass-by-value: The subroutine receives an isolated duplicate copy of the argument. If the function changes the parameter, the caller’s variable remains completely unchanged.
- Pass-by-reference: The subroutine receives the actual memory location of the caller’s variable. Any mutation directly changes the original data in the caller’s scope. Arrays and object instances are typically passed by reference to avoid the performance cost of copying massive blocks of data in memory.
Check yourself
Subroutines and parameters
Quick questions, made fresh every time and marked here. Do a few until they feel easy.
Exam practice
Paper 1-style questions
3 questions · 8 marks
Write your answer as you would in the exam, then show the mark points and tick each one your answer made. These are our own questions in the style of the exam, not past-paper questions.
1.Distinguish between a function and a procedure.
[2]Distinguish: Make the differences between two things clear.
2.Compare pass-by-value and pass-by-reference parameter passing mechanisms in terms of memory, caller mutation, and typical data types.
[4]Compare: Similarities and differences, about both things, point by point.
3.Explain two software engineering benefits of breaking a large program into modular subroutines.
[2]Explain: Give reasons: say what happens AND why, or how one thing causes another.
In a nutshell
- Modular programming breaks software into discrete, reusable functions and procedures.
- Functions compute and return a value; procedures perform actions and return void.
- Pass-by-value passes a copy of the argument, preventing side effects in caller variables.
- Pass-by-reference passes the memory address, allowing the subroutine to mutate caller data directly.
