Java

TOPIC 31 – MODULAR PROGRAMMING

 

 

LESSON NOTE

 

 

MODULAR PROGRAMMING

 

Modular programming is a programming style or technique that sees an advanced program be separated into several smaller program parts (modules).  The goal is to have each module be well defined and independent of other modules.

 

ADVANTAGES

 

Modular programming allows for easier code testing and error detection.

 

Another key advantage is that modular programming breaks down large complex applications into many smaller simpler programs (or modules).

 

DISADVANTAGES

 

When running an application that consists of many different parts, there is usually a little bit of processing required to make these parts work together.  So modular programming could lead to less efficient code.

 

FUNCTIONS AS MODULES

 

We can use functions to separate an application into different parts.  For example, a simple game could be broken down into different unrelated parts (see below).

 

SIMPLE EXAMPLE

 

In the following code, the main function of a Game is broken down into three parts – the intro to the game, the game itself and the conclusion section.  All three sections are dealt with in different functions (implementation not shown) and can be done by different programmers.

 

public class Game

{

   public static void main(String[] args)

   {

        GameLib.showIntro();

        GameLib.playGame();

        GameLib.showGaveOver();

   }

}

 

REALITY

Reality is that there usually is some information that has to be shared between each module or section.  We can do this with functions by using parameters and return values.

 

ANOTHER EXAMPLE

 

In the program below, information is passed to and from the different functions.  Still, at the Game class level, the complexity is very simple to deal with.

 

public class Game

{

   public static void main(String[] args)

   {

        GameLib.showIntro();

        String name = GameLib.getPlayerName();

        int score = GameLib.playGame(name);

        GameLib.showFinalScore(score);

   }

}