Programming Basics for Duncan IV: Subs and Functions

In programming you’ll find that you want the computer to do the same thing again and again, usually something pretty basic. Early on, programmers decided that they didn’t want to write the same instructions again and again so they developed subroutines and functions.

A subroutine is a snippet of code that you can abstract so it can be used again and again. It can be dead simple like this one that makes the computer beep, twice:

SUB BeepTwice
BEEP
BEEP
END

You write this at the start of the program, so later when you use it the computer knows what to do.

SUB BeepTwice
BEEP
BEEP
END

CALL BeepTwice

This is handy if you want to summarise a bit of complicated code that does one thing, like advance the paper in a printer or turn a light on, but it’s not very flexible. It would be better if we could get it to do things depending on values/variables. We can pass parameters to the subroutine so it can make decisions. That looks like this:

SUB FireAlarm (isHouseOnFire)
IF isHouseOnFire = true THEN
do things that sound the alarm and turn on the sprinkler system
END

CALL FireAlarm(x)

Now we are getting somewhere! We can make loops that call subroutines instead of writing out the same code over and over. This is a powerful tool. But what if we don’t want the subroutine to do something but to do a calculation or give an output? That when we call it a function. Functions are borrowed from maths, again, and they take in parameters and give back a result when they are done. This result is always a value. Here’s a simple example:

FUNCTION add(x, y)
return x+y
END

add(5,5)

The result is 10. Functions are useful because they give you a result of some type, even if that result is a confirmation that everything worked as expected. These days people only use functions, not subroutines. With functions you can abstract your code to be more understandable, so that complex things are hidden away like:

IF getTemprature(“kitchen”) > 100 THEN FireAlarm(true)

If you wrote out the logic for all these things that are hidden away in the function then it would be a big, long mess. This one-liner is very easy to understand what’s going on.

Leave a Reply

Your email address will not be published. Required fields are marked *