5.3 Methods


5.3 Methods

As mentioned in Chapter 4, a program is normally decomposed into classes, and classes are divided into methods or functions. Methods are the smallest decomposition units. A function represents a small subtask in the class. Figure 5.2 illustrates the general structure of a function. This structure consists of:

  • The local data declarations

  • A sequence of instructions


Figure 5.2: General structure of a function.

The data declared within a function is known only to that function—the scope of the data is local to the function. The data in a function only exists during execution of the function; their persistence is limited to the lifetime of the function.

Every function has a name, which must be meaningful and should be the name of the subtask carried out by the function. The name of the function is used when it is called or invoked by some other function. The purpose of the function is described in the description paragraph, which ends with a star-slash (*/). The KJP statement that defines the basic structure of a function is:

        description               .  .  .             */        function  function_name  is              constants                  .  .  .              variables                  .  .  .              objects                  .  .  .              begin                  .  .  .        endfun  function_name  

In the structure shown, the keywords are in boldface. The first line defines the name of the function at the top of the construct. In the second line, the description paragraph includes the documentation of the function.

The data declarations define local data in the function. These are divided into constant declarations, variable declarations, and object declarations. This is similar to the data declarations in the class. The local data declarations are optional. The instructions of the function appear between the keywords begin and endfun. The following KJP code shows a simple function for displaying two text messages on the screen.

       description          This function displays the initial message for          the program on the screen. */       function display_message is       begin          print "Starting program."          print "Computing standard deviation of rainfall                                                     data"       endfun display_message 




Object-Oriented Programming(c) From Problem Solving to Java
Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)
ISBN: 1584502878
EAN: 2147483647
Year: 2005
Pages: 184

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net