Subroutines are the last building block to talk about. They're also called procedures.

A sub is a bunch of code with a name, like getInput, or computeHappiness. A simple idea, with big effects.

Subs help with encapsulation. Encapsulation is a Very Important Idea in programming. Take a chunk of code, pull it out the main program, and treat is a separate entity.


  • Make the chunks of your program more visible, making code easier to read, and easier to change. A sub is the code for one chunk, more or less.
  • Let teams work together. Different programmers work on different chunks at the same time, by writing a sub for each chunk. Put the subs together, and you have a working program.
  • Let you reuse code. For example, if users enter eight pieces of data, you could write validation code for each one, that is, eight chunks of validation code. Or you could write one sub that works for all of them.

Let's start with some wine.