Intro to Modules

Chapter 3: Modules

A module is a group of statements that exist for the purpose of performing a specific task within a program.

Our payroll program from the last section simply multiplied hours worked by the hourly rate. A more realistic payroll program would do much more.

  • Get hourly rate
  • Get hours worked
  • Calculate gross pay
  • Calculate overtime pay
  • Calculate taxes
  • Calculate net pay
  • Print pay check

Most programs perform tasks that are large enough to be broken down in to several subtasks. This is why programmers often break down their programs in to modules. A module is a group of statements that exist within a program for the purpose of performing a specific task.

Divide and Conquer

Instead of writing one large program as a long sequence of statements, they can be written as several small modules, each performing a specific part of the task. We can then execute the small modules in the desired order to perform the overall task. We simply divide a large task in to several smaller tasks.

When using modules, we isolate each task within the program in its own module. Our pay calculating program could be divided into the following modules.

  • A module that will Get hourly rate
  • A module that will Get hours worked
  • A module that will Calculate gross pay
  • A module that will Calculate overtime pay
  • A module that will Calculate taxes
  • A module that will Calculate net pay
  • A module that will Print pay check

Every modern programming language allows us to create modules. Modules can be called procedures, subroutines, subprograms, methods, and functions. A function is actually a special type of module we'll discuss later.

Benefits of Using Modules

A program benefits in the following ways when modularized:

  • Simpler Code - Keeps things simple, easier to read and understand. Several small modules are much easier to read than a long sequence of statements.
  • Code Reuse - reduces duplication of code within a program. We write code once to perform a task, then reuse it anytime we need to perform that task.
  • Better Testing - easier to debug. We test each module individually making it easier to isolate and fix errors.
  • Easier Maintenance - easier to maintain. All programs need maintenance - need to be modified to correct logic errors, improve performance, and provide a better user experience. With modules, our code is simpler, smaller, and easier to understand.
  • Faster Development - many tasks are common to different programs. Tasks such as creating a login screen can be placed in modules that can be easily incorporated into different programs.
  • Better Teamwork - easier to divide work. Different programmers can work on different modules.