Modules (Methods)

When a program is just one long piece of code, maintenance and testing of that code is a nightmare. Professional programmers measure their code in KLOC – thousands of lines of code. If you were writing a program that long and your boss told you to switch “the order of things in the edit menu”, you are going to be in trouble. It will be very difficult to find that section.

The solution to this problem is to break the program into smaller pieces, called modules. A module is a piece of code that your program can call to perform a method for it. You have already used premade methods in applets – the paint, init, action methods. 

Modules should be:

Simple Methods

Methods can be something like formulas that you use in math of science. The formulas have unknowns in them. You plug in the values for the unknowns from the problem and use the formula to calculate the answer. For example:

Calculate the velocity of a car that starts driving at 0 seconds and finishes at 10 seconds. In that time it drives from a point 20 meters away from you to a point 80 meters away from you.

Formula: Velocity = (change in distance) / (change in time)

Change in distance = Ending distance – Starting distance

Change in time = Ending time – Starting time

Data:

Therefore, 

Velocity = (80-20) / (10-0) = 6 meters / second

With a method, you get all of the data it needs to make its calculations or do whatever it is supposed to do. Then, you pass it the information and it does the calculations (or whatever) for you. For example, the above problem solved with a computer is:

import java.io.*;    
public class velocity
{
   public static void main (String args    [])
   {
     double starttime, endtime, startdist,enddist, velocity; 
     System.out.println ("This program calculates velocity.");
     starttime = IBIO.inputDouble ("Please enter the starting time: ");
     endtime = IBIO.inputDouble (" Please enter the finishing time: ");
     startdist = IBIO.inputDouble ("Please enter the starting position: ");
     enddist =IBIO.inputDouble(" Please enter the finishing position: "); 
     velocity = v (starttime, endtime, startdist, enddist);
     System.out.println ("The velcity is: " + velocity); 
   }    
    public static    double v (double t1, double t2, double d1, double d2)
   { //The function's actual code
     return ((t2 - t1) / (d2 - d1)); 
   } 

Note that the variables passed to the method need to have a type. If the main program tries to pass variables that are not that type, the program will not be compiled and you won’t be able to run it.

The diagram at the side shows the order in which the program statements are executed when the code is run:

AN IMPORTANT NOTE: static needs to appear in the function declaration line in void main programs. Static should NOT appear in the function declaration in applets.