Methods
In this chapter
- Describe the terms subroutine, method, procedure and function
- Define and call your own subroutines
- Use parameters and arguments to pass values to a subroutine
- Use return statements to return values back to the function call
- Know the difference between passing by value and passing by reference
- Know the difference between local and global variables
- Identify advantages of using subroutines​
As the problems we want to solve get larger, and presumably harder, it makes sense to split the algorithm into smaller sub-problems. When taken separately these smaller sub-problems are easier to solve and if we solve all the sub-problems we'd have solved the larger one! This is a process of breaking a larger problem into a set of smaller sub-problems is known as decomposition.
Each sub-problem can have its own section in our code taking responsibility for handling just that part of the problem. These sections are known as subroutines, or methods in C#. You'll also encounter the terms procedure and function. These terms do have a specific meaning as we'll see in this chapter as a method can be either a procedure or a function:
- function: functions return a value to where the function was called
- procedure: does not return a value
There are very good reasons to use methods in our program code:
- The code will be structured better
- The code will be more readable
- Duplication will be kept to a minimum (Don't Repeat Yourself (DRY) is a good maxim to adopt)
- Code can be re-used
Of course, we have already used a method, all the code examples we've looked at thus far had a Main()
method. This is the entry point to our programs, it is the main method in the Program class.
From the syllabus
AQA: Subroutines (procedures/functions) (3.1.1.10/4.1.1.10)}
- Be familiar with subroutines and their uses. Know that a subroutine is a named 'out of line' block of code that may be executed (called) by simply writing its name in a program statement. Be able to explain the advantages of using subroutines in programs