
\documentclass[11pt]{article}
\setlength{\textwidth}{5.5in}
%\setlength{\evensidemargin}{-0.5in}
\usepackage{TRmydraft} % title page report
\usepackage{wmff} % algorithm
\usepackage{yprob} % algorithm listing, code, report exercises

\usepackage{graphicx}

\pagestyle{myheadings}
\markright{Functions\hfill}

\begin{document}

\reptitle{\bf Functions}
\author{Dr. Jos\'e M. Garrido}

%\date{February, 2009}

\subtitle{{}}
\subsubtitle{}


\authoraffil{Department of Computer Science} 
 
%
%\halftitlepage
%

\titlepage

\mdraft
%\maketitle
%\newpage
%\tableofcontents
%\newpage

\section{Function Implementation}

A program is normally decomposed into classes, and classes are divided into methods or functions. 

As mentioned previously, data\index{data} declared within a function is known only to that function---the scope of the data is {\em local\/}\index{local data} to the function. The data in a function has a limited lifetime, it only exists during execution of the function. 

The name of the function is used when it is called or invoked by some other function. The relevant documentation of the function is described in the {\bf description} paragraph, which ends with a star-slash (*/). The OOSimL statements for defining a function are:

%\newpage

\vspace{0.1in}
%\begin{quote}
{\tt %\small 
\begin{algorithm}
{\bf description}
\ \ \ . . .
\ \ */
{\bf function} $\langle${\em function\_name} $\rangle$ {\bf is}
\ \ {\bf constants}
\ \ \ \ . . .
\ \ {\bf variables}
\ \ \ \ . . .
\ \ {\bf object references}
\ \ \ \ . . .
\ \ {\bf begin}
\ \ \ \ . . . [instructions]
{\bf endfun} $\langle${\em function\_name} $\rangle$ 
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}


The data declarations are divided into constant declarations, variable declarations, and object declarations. This is similar to the data declarations that appear in the class. These declarations define local data\index{data} in the function and are optional. The instructions\index{instructions} of the function appear between the keywords {\bf begin} and {\bf endfun}. The following OOSimL code shows a simple function for displaying a text message on the screen. 


\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
description
   This function displays a message 
   on the screen. */
function show_message is
begin
   display "Computing data" 
endfun show_message 
\end{verbatim}
%\end{quote}
}
%\vspace{0.1in}

\section{Function Calls}

A function starts executing when it is called by another function. A function {\em call\/}\index{call} is also known as {\em method invocation}\index{method invocation}. The function that calls another function is known as the calling function; the second function is known as the called function. When a function calls or invokes another function, the flow of control is altered and the second function starts execution. When the called function completes execution, the flow of control is transferred back (returned) to the calling function. This function continues execution from the point after it called the second function. 

After completion, the called function may or may not return a value to the calling function. From the data transfer point of view, there are three general categories of functions:

\begin{enumerate}
  \item
   {\em Simple functions\/} are functions that do not return any value when they are invoked. The previous example, function {\em show\_message}, is a simple (or void) function because it does not return any value to the function that invoked it.
  \item
   {\em Value-returning\/}\index{value-returning} functions that return a single value after completion.
  \item 
   Functions with {\em parameters\/}\index{parameters} are functions that require one or more data items as input values when invoked.
\end{enumerate}

Functions that combine the last two categories ---functions that return a value and that have parameters are also grouped in two categories, according to their purpose:

\begin{itemize}

\item
Functions that return the value of an attribute of the object and do not change the value of any attribute(s) of the object. These are known as {\em accessor\/}\index{accessor} functions. 

\item
Functions that change the state of the object in some way by altering the value of one or more attributes in the object. Normally, these functions do not return any value. These are known as {\em mutator\/} functions\index{mutator}.

\end{itemize}

%\hspace{0.3in}

Good programming practice recommends defining the functions in a class as being either accessor or mutator.

\subsection{Calling Simple Functions}

Simple functions do not return a value to the calling function. An example of this kind of function is {\em show\_message}, discussed previously. There is no data transfer to or from the function. In OOSimL, the statement that calls or invokes a simple function that is referenced by an object reference variable is:

\vspace{0.1in}
%\begin{quote}
{\tt %\small
\begin{algorithm}
{\bf call} $\langle${\em function\_name} $\rangle${\bf of} $\langle${\em object\_reference} $\rangle$ 
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}


In the following example, function {\em show\_message\/} that belongs to an object referenced by {\em carobj\/}, is invoked from function {\em main}, the call statement is:

\vspace{0.1in}
%\begin{quote}
{\tt \footnotesize
\begin{algorithm}
{\bf call} show\_message{\bf of} carobj
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}

Figure~\ref{fig:funcall} shows the calling function and the called function, {\em show\_message}. After completing its execution, the called function returns the flow of control to the calling function. 


\begin{figure}[h]
\vspace{.1in}
\centereps{3.5in}{1.804in}{figs/funcall.eps}
\caption{The calling and called functions}
\label{fig:funcall}
%\vskip\baselineskip
\vspace{0.1in}
\end{figure}

%\section{Data in Function Calls}

Data can be transferred\index{data transfer} between the calling and the called function. This data transfer may occur from the calling function to the called function, from the called function to the calling function, or in both directions. 


%\newpage

\subsection{Value-Returning Functions}

Value-returning functions transfer data from the called function to the calling function. In these functions, a single value is calculated or assigned to a variable and is returned to the calling function. 

The called function is defined with a type, which is the type of the return value. The function {\em return type\/}\index{return type} may be a simple type or a class. After the execution of the called function completes, control is returned to the calling function with a single value. The OOSimL statements that define the form of a value-returning function are:

\vspace{0.1in}
%\begin{quote}
{\tt %\small
\begin{algorithm}
{\bf description}
\ \ . . .
\ */
{\bf function} $\langle${\em function\_name} $\rangle${\bf of type} $\langle${\em return\_type} $\rangle$ {\bf is}
\ \ . . .
\ \ {\bf return} $\langle${\em return\_value} $\rangle$ 
{\bf endfun} $\langle${\em function\_name} $\rangle$
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}

The value in the return statement can be any valid expression, following the {\bf return}\index{return} keyword. The expression can include constants, variables, object references, or a combination of these. 


The following example defines a function, {\em get\_name} that returns the value of the attribute {\em emp\_name} of an object of class Employee. This value is returned to the calling function. In the header of the function, the type of the value returned is indicated as {\bf string}. The code for this function definition is:

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
  description
    This function returns the name of the employee object.
    */
  function get_name return type string is
  begin
      return name 
  endfun get_name
\end{verbatim}
}
\vspace{0.1in}

%\subsubsection{Invoking Value-Returning Functions}

The value-returning function can be called and the value returned can be used in several ways:

\begin{itemize}
 \item
 Call the function in a simple assignment statement
 \item
 Call the function in an assignment with an arithmetic expression
 \item
 Call the function in a more complete {\em call\/} statement
\end{itemize}

The value returned by the called function is used by the calling function by assigning this returned value to another variable. The following example shows a function calling function {\em get\_salary\/}. The calling function assigns the value returned to variable {\em sal}. There are several ways to write this code and the statements are:

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
set sal = call get_salary 
call get_salary value to sal
set sal = get_salary()
\end{verbatim}
}
\vspace{0.1in}

The value returned can be used in an assignment with an arithmetic expression after calling a function. For example, after calling function {\em get\_salary\/}, the value returned is assigned to variable {\em sal}. This variable is then used in an arithmetic expression that multiplies {\em sal\/} by variable {\em percent\/}. The value that results from evaluating this expression is assigned to variable {\em upd\_sal\/}. This assignment statement is:

%\vspace{0.2in}
\begin{quote}
\tt %\footnotesize
\begin{verbatim}
set upd_sal = sal * percent 
\end{verbatim}
\end{quote}
\rm %\normalsize 
%\vspace{0.1in}
 
%\vfill

\subsection{Function Calls with Arguments}

The called function can receive data values when called from another function. The functions definition for functions to be called should include data definitions known as {\em parameter\/}\index{parameters} {\em declarations}. These parameter definitions are similar to local data declarations and have local scope and persistence. The called function may return a value, although it is not recommended to define the called function for this.

%\subsubsection{Calling Functions with Parameters}

The data values sent to the called function by calling function are known as {\em arguments\/}\index{arguments} and can be actual values (constants) or names of data items. When there are two or more argument values in the function call, the argument list consists of the data items separated by commas. The argument list should appear after the keyword {\bf using} in the {\bf call} statement. The OOSimL {\bf call} statement for a function call with arguments is:

\vspace{0.1in}
%\begin{quote}
{\tt %\small 
\begin{algorithm}
{\bf call} $\langle${\em function\_name} $\rangle${\bf of} $\langle${\em object\_ref} $\rangle$
\ \ \ \ \ \ \ {\bf using} $\langle${\em argument\_list} $\rangle$ 
\end{algorithm}
%\end{quote}
}
%\rm %\normalsize
\vspace{0.1in}

The following example is a call to function {\em cal\_area\/} that belongs to an object referenced by {\em myobj}. The function calculates and displays the area of a triangle given two arguments {\em x\/} and {\em y}. This {\bf call} statement is:

\vspace{0.1in}
\begin{quote}
{\tt %\footnotesize
\begin{verbatim}
  call cal_area of myobj using x, y 
\end{verbatim}
}
\end{quote}
\vspace{0.1in}

%\subsubsection{Declaration of Parameters}

The declaration of parameters\index{parameters} in a function defines for every parameter a type and a parameter name. The general structure of a function with parameter declaration is:

\vspace{0.1in}
%\begin{quote}
{\tt %\footnotesize
\begin{algorithm}
{\bf description}
\ \ . . .
\ */
{\bf function} $\langle${\em function\_name} $\rangle$ 
{\bf parameters} $\langle${\em parameter\_list} $\rangle$ 
{\bf is}
\ \ . . .
 
{\bf endfun} $\langle${\em function\_name} $\rangle$ 
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}

In the following example, function {\em cal\_area} computes the area of a triangle given the base and altitude. The code for the function in OOSimL is:

\vspace{0.1in}
\begin{quote}
{\tt %\small 
\begin{verbatim}
description
  This function calculates the area of
   A triangle given the base b and the height h
   it then prints the result on the screen.
  */
function cal_area 
parameters b of type float, 
           h of type float
is
variables
   define area of type float   // local variable
begin
   set area = b * h * 0.5 
   display "Area of triangle is: ", area 
   return                      // empty return
endfun cal_area
\end{verbatim}
}
\end{quote}
\vspace{0.1in}


In the example, function {\em cal\_area\/} declares the parameters {\em b\/} and  {\em h}. The parameters are used as placeholders for the corresponding argument values transferred from the calling function. Figure~\ref{fig:fparam} illustrates the call of function {\em cal\_area\/} with argument values from the calling function. 

\vspace{.1in}
\begin{figure}[h]
\centereps{2.15in}{3.378in}{figs/fparam.eps}
\caption{Using arguments in a function call}
\label{fig:fparam}
%\vskip\baselineskip
\end{figure}
\vspace{0.1in}

\section{Constructors}

One or more {\em constructors\/}\index{constructor} functions, also known as {\em initializer\/}\index{initializer} functions, will normally appear in a class definition. These are special functions that are called when creating objects of the enclosing class. The main purpose of an initializer function is to set the object created to an appropriate initial state. The attributes of the corresponding object are assigned to some initial values.

In the following example, class {\em Employee\/} include the attribute declaration and the definition of the initializer function.

%\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
class Employee is
  private
  variables                   
      define salary of type double
      define age of type integer
      define name of type string
      define sal_increase of type double  
  object references
      define employ_date of class EmpDate   
  public    
  description
    This is the constructor, it initializes an Employee 
    object on creation.    */
  function initializer 
  parameters iname of type string, 
             isalary of type double, 
             iage of type integer
  is
  begin
    set salary = isalary
    set age = iage
    set name = iname
    set sal_increase = 0.0
    set employ_date = null
  endfun initializer 
  . . . [other functions in the class]
  endclass Employee
\end{verbatim}
%\end{quote}
}
\vspace{0.1in}

It is recommended to define at least a default initializer function. When no initializer function appears in the class definition, the default values are (zero and empty) assigned to the attributes. 

In class {\em Employee} the default values for the {\em sal\_increase\/} attribute is set to 0.0. 

An initializer function can set the value of the attributes to the values given when called. These values are given as arguments in the statement that creates the object. The general statement to create an object with given values for one or more attributes is:

\vspace{0.1in}
%\begin{quote}
{\tt %\small 
\begin{algorithm}
{\bf create} $\langle${\em object\_ref\_name} $\rangle${\bf of class} $\langle${\em class\_name} $\rangle$
\ \ \ {\bf using} $\langle${\em argument\_list} $\rangle$
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}

The following example uses an object reference {\em emp\_obj\/} of class {\em Employee} to create an object with initial values of {\tt "John Doe"} for {\em name},  {\tt 35876.00} for {\em salary}, and {\tt 45} for {\em age}.

\vspace{0.1in}
\begin{quote}
{\tt \small 
\begin{verbatim}
 create emp_obj of class Employee 
                        using "John Doe", 35876.00, 45
\end{verbatim}
}
\end{quote}
\vspace{0.1in}

{\em Overloading\/}\index{overloading} is the programming facility of defining two or more functions with the same name. This facility of the programming language allows any function in a class to be overloaded. These functions are defined with the same name, but with a different number of and types of parameters. In this way, there is more than one way to initialize an object of the class. 


%\newpage

\section{Complete Sample Program}

\label{sectcomprog}
The following example is a complete program that consists of two classes: class {\em Employeem\/} and class {\em Comp\_salary\/}. The definition of class {\em Employee} is as follows:

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
description
  This program computes the salary increase for an employee;
  if his/her salary is greater than $45,000 the salary 
  increase  is 4.5%, otherwise the salary increase is 5%.
  This is the class for employees. The main attributes are
    salary, age, and name.  */
class Employeem is
  private
  variables                    // variable data declarations
      define salary of type float
      define age of type integer
      define obj_name of type string
      define salincrease of type float   // salary increase
  public
  description
    This is the constructor, it initializes an object on 
    creation.     */
  function initializer 
  parameters iname of type string, 
             isalary of type float, 
             iage of type integer 
  is
  begin
    set salary = isalary 
    set age = iage 
    set obj_name = iname 
  endfun initializer 
  description
    This funtion gets the salary of the employee object. */
  function get_salary return type float is
    begin
      return salary 
  endfun get_salary 
  description
    This function returns the name of the employee object. */
  function get_name return type string is
    begin
      return obj_name 
  endfun get_name 
  description
      This function computes the salary increase and 
      updates the salary of an employee.       */
  function sal_increase is
    constants   // constant data declarations  
      define percent1 = 0.045 of type float 
      define percent2 = 0.050 of type float 
    begin                // body of function starts here
      if salary > 45000.00 then
         set salincrease = salary * percent1 
      else
         set salincrease = salary * percent2 
      endif 
      add salincrease to salary    // update salary
  endfun sal_increase
  description
     This function returns the salary increase for 
     the object. */
  function get_increase return type float is
   begin
     return salincrease
  endfun get_increase
endclass Employeem 
\end{verbatim}
%\end{quote}
}
\vspace{0.1in}

The other class, {\em Comp\_salary\/}, includes function {\em main\/} that starts and controls the execution of the entire program. The following code is the implementation of class {\em Comp\_salary}.


\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
description
  This program computes the salary increase for an employee;
  if his/her salary is greater than $45,000 the salary 
  increase is 4.5%, otherwise the salary increase is 5%. 
  This class creates and manipulates the objects of 
  class Employeem. */
class Comp_salary is
  public
  description
      This is the main function of the application.
      */
  function main is
    variables
      define increase of type float
      define salary of type float
      define age of type integer
      define empname of type string
    object references
      define emp_obj of class Employeem
    begin
      display "Enter salary: " 
      read salary 
      display "Enter age: " 
      read age 
      display "Enter employee name: " 
      read empname 
      create emp_obj of class Employeem using 
                            empname, salary, age 
      call sal_increase of emp_obj
      set increase = call get_increase of emp_obj 
      set salary = get_salary() of emp_obj // updated salary
      display "Employee name: ", empname 
      display "increase: ", increase, " new salary: ",
                                                salary 
   endfun main 
endclass Comp_salary
\end{verbatim}
%\end{quote}
}
\vspace{0.1in}


\section{Static Features}

Functions or attributes in a class may not be associated with any object of the class. These features are known as {\em static\/}\index{static} features and do not belong to an object, although they are defined in a class. To access these features, the class name followed by a dot and then the name of the feature is used. The following example invokes method {\em cos\/} of class {\em Math}: 

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{verbatim}
set angle = Math.cos(x) * delta
\end{verbatim}
}
%\end{quote}
\vspace{0.1in}


To define a static function, the keyword {\bf static} is written before the name of the function. The following example is the header for the definition of method {\em compute\_h}:

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
static function compute_h is
. . .
endfun compute_h
\end{verbatim}
}
%\end{quote}
\vspace{0.1in}

In a similar manner, the declaration of a static\index{static} attribute is written with the keyword {\bf static} before the variable declaration. These variables should normally be private and should be accessed by (public) accessor functions. When the program executes, for every declaration of a static variable, there is only one copy of its value shared by all objects of the class. Often, static variables are also known as class variables, and static methods as class methods.

The following example declares a static variable named {\em count\_pins} and initializes it to value 20.

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
static count_pins = 20 of type integer
\end{verbatim}
}
%\end{quote}
\vspace{0.1in}


%\newpage


\end{document}
