The Computing Tutor's Four Rules for Writing Functions or Procedures
As someone studying A level computer science or BTEC IT or Computing, at some point you will need to write a function, method, procedure or sub-routine. They are all essentially the same thing - they are just called different names in different languages. For example, in C# - everything is a function - they are defined by their return type - a VOID function brings back nothing to the calling program, where as RETURN function brings something back. In VB and VB.NET you have a METHOD which goes away and does something, and you have a PROCEDURE that goes away and brings something back.
Same thing, different names.
However, in all languages the way you structure them is the same, and I'm going to talk you through it.
Lets take a very simple function - it will prompt a user to enter two numbers, it will add them together and then display the result.
The output should look like this:
OK the logic of our code should be:
output to the user
store the input as a string
convert the strings to numbers
add the two numbers together
output the result
OK, all pretty simple, right?
well when we start to break it down, writing this simple function contains all the rules for pretty much every function on the planet. I call them Meaney's Rules and they will help you put your functions together.
RULE NUMBER 1 - DECLARE YOUR VARIABLES!
All you variables should be declared at the start of your function. It keeps things simple and you know exactly what's in your function.
You will need a variable to store each piece of user input, you will need variables to store the results of any calculation, and you will need variables to store any data conversion. Here we are changing strings to numbers.
Here are the variables you will need in the simple calculator function in C#
RULE NUMBER 2 - HANDLE THE INPUT!
You will need to output a message to the user and then store all the input as a string.
If you have a function with parameters, you might want to capture these and store the data in a temporary local variable, either way - you will need to deal with data coming into your Function.