2.1 General concepts

A subroutine is a block of code that has a name. Such a block of code remains “dormant” until the subroutine is invoked. Invoking a subroutine is also called “calling” a subroutine.

A subroutine can be “invoked” by its name from various places. When a subroutine is invoked, the block of code contained executes.

This means that subroutines can be used in place of the usual copy-and-paste approach of using the same block of code at various places. There are several benefits to the use of subroutines in place of copy-and-paste.

2.1.1 Debug once, debug all

Using the copy-and-paste approach, debugging a program can be time consuming. For example, let us assume that a block of code has a bug before it was copied-and-pasted. When the bug is discovered, all copies of the code need to be fixed. Unfortunately, it is often difficult to locate all the “clones” from pasting the original code. As a result, some bugs may escape from an initial attempt to fix the bugs.

When a subroutine (and invocations of that) is used, then a bug in the subroutine only needs to be fixed once. Each invocation does not actually contain any logic, it is merely a reference to the subroutine.

2.1.2 More compact code

It is intuitive that a program that uses copy-and-paste to replicate code is considerably larger in size than one that use subroutines and invocations of subroutines. This is because the invocation of a subroutine uses very little space in a program. Each clone of a copy-and-paste method, however, consumes the same amount of space as the original copy (that was copied and pasted).

2.1.3 Better structured code

Subroutines can also help structure the code of a program better. This particular benefit of subroutines is important to any large programs. The benefit is due to the ability to invoke a subroutine from another subroutine.

The necessity to use subroutines to organize code is clear when the logic requires hundreds of lines of code. In commercial programming, hundreds of lines of code is an insignificant amount of code!

If subroutines are not used to organize code, then a programmer needs to develop and debug hundreds of lines of code. This can be quite difficult because the beginning and the end of a construct (such as if...then and end if, or do while... and loop) cannot be located easily.

It is best to make sure the beginning and the end of a construct be visible on the same page in an editor, such as the Visual Basic editor. However, this also means that we can only have up to 50 or 60 lines, at the most, even with a large monitor and small font size.

How do we fit hundreds of lines into 60 lines? We cannot.

Unless, of course, that we somehow chop up the hundreds of lines of code to chunks of 60 lines or less. This can be done by the use of subroutines.