\chapter{Object-Oriented Programming\label{chap:oop}}

% ====================================================================== 

\section{Introduction} 

Object-oriented programming (OOP) is a popular term in the programming community. It represents
an alternative approach of programming to cope with program development in the large. As I outlined
in the previous chapter, maintenance of large scale programming projects become increasingly 
difficult as the size of code base increases. Object-oriented programming is seen by many in the
Software Engineering community as a desirable solution to keep complex programming projects
in order. In the text below we would explore the rationale behind this argument and point out how
object-oriented model can help alleviate some of the deficiencies in the plain old procedural model. \\

Perl started to support the notion of object-oriented programming in Perl 5. In fact, most of the 
necessary concepts that you need to understand object-oriented programming in Perl has already been
covered in the previous chapters, and frankly, not much content are left for this chapter. However,
because of the importance of object-oriented programming, and in order to avoid making the previous chapters 
too long if I lump them together, I have to dedicate a chapter to object-oriented programming. Compared
with previous chapters, you will find longer and more complete examples in this chapter, so as to 
help you familiarize with OOP in a more practical context.
You should flip back to the previous chapters if you have not read them carefully, because the Perl
implementation of OOP is based on subjects studied in the previous chapters. In other words, knowledge
of packages, scope, subroutines and references is a prerequisite to understanding OOP in Perl. \\

%one of the programming paradigms adopted (http://www.wikipedia.org/wiki/Programming_paradigm)

%represents the trend 

If you have previously programmed in some other object-oriented programming languages like
Java and C++, you may safely skip the section ``Object-oriented Concepts'' below. However,
because the Perl implementation of OOP is very much different from other languages like PHP,
Java and C++, you should not skim read the remaining sections as you would find the Perl approach
to object-oriented programming alien to you (it happened to me as well when I learned Perl
with some knowledge in C++), and there are some traps to which programmers who have written object-oriented
programs in other languages are vulnerable. Please keep this in mind when you are reading 
this chapter. \\

% ====================================================================== 

\section{Object-Oriented Concepts}

\subsection{Programming Paradigms}

The syntax of a programming language is largely influenced by the \term{programming paradigm}
on which the language is based. A programming paradigm represents a framework which describes
in a general, language-independent way how syntactic language elements are organized and processed.
Without delving deep into a formal definition of programming paradigms, which is far beyond the
scope of this tutorial, I would rather state in a more casual way that a programming paradigm
is supported by a school of thoughts to address a specific subset of programming tasks. Therefore,
it is generally not appropriate to strictly claim that one paradigm is always better than the other.
However, I personally believe if properly implemented, a properly-written object-oriented program 
is easier to maintain, and allows for a larger basis of extension by leveraging the power of 
object-oriented programming, for reasons that I would explain later in this section. \\

%The computer science community has a notion of \term{design pattern}
%which describes the best practice 
There are various programming paradigms in use today. However, the majority of programmers adopt either
one of two major paradigms, namely procedural programming and object-oriented programming. \\

Our discussion so far has been solely based on the procedural programming paradigm. A complicated
program is broken down into smaller pieces by delegating pieces of the source code to subroutines.
and external source files. Variables are created and updated directly to maintain program state during execution. \\

Object-oriented programming should not be considered a total revamp of procedural programming.
Instead, it is best considered one that uses procedural programming as the basis with the emphasis
on the way different logical components (i.e. classes) interact with each other. It enforces
a more well-defined way of grouping related subroutines and data into a logical entity, and this
is the foundation of object-oriented programming. \\ 

For an executive summary of the various programming paradigms, please visit the 
\link{http://www.wikipedia.org/wiki/Programming\_paradigm}{Wikipedia.org} entry on programming
paradigm. Be prepared, they are conceptual computer science topics that cannot be easily understood. \\

\subsection{Basic Ideas}

As I mentioned in the previous section, the idea of object-oriented programming is to group related
subroutines and data into logical entities, each of which constituting its own domain. Such logical
entities are known as \term{classes}. Each class defines a framework which describes the set of properties
and behaviours of \term{objects} created (\term{instantiated}) from the class. \\

Consider an airplane and a car. Because a car and an airplane have different characteristics and
exhibit different behaviours (e.g. fly vs. move) we model them using two different classes. In other
words, each class represents a certain type of object. In a class, behaviours are implemented as 
\term{methods}, which are subroutines associated with a class. For example, an airplane class would
very likely include an \texttt{ascend()} method and a \texttt{descend()} method which contain the
program needed for escalation and landing of an airplane. Also, different classes are likely to have different
\term{properties}. For example, an airplane is likely to maintain an \texttt{altitude} property to
track down the current height of the airplane above the ground. On the other hand, a car would not 
have this property. A class only defines the properties. The values of which are maintained independently
in each class instance. \\

After we have established a class, we need to create a class instance which is called an object. When
a class instance (an object) is created, it possesses all the methods of the class and, as noted in
the previous paragraph, each object holds an instance of the properties. This arrangement allows each
object to carry its own set of property values. For example, consider a \texttt{Car} class which has only one
property \texttt{colour} and one method \texttt{move()}. When we create several objects from the 
\texttt{Car} class, each of them ``inherits'' the method from the class and maintains a value representing
the colour of the object. \\ 

\subsection{Fundamental Elements of Object-Oriented Programming}

An object-oriented programming language needs to qualify three fundamental properties, namely \term{encapsulation},
\term{inheritance} and \term{polymorphism}. These principles are fundamental to support the virtues of
object-oriented programming. \\

Adapted from Wikipedia.org, encapsulation refers to \textit{the practice of hiding data structures which represent the internal state of
an object from access except through public methods of that object}. Basically, that implies you should not
change a property by directly modifying the internals of an object. Instead, you should modify it through
the \term{interface} of the object. An interface is what is expected to be seen from outside of the object.
In Perl, this includes all object methods. For example, while an airplane object maintains the \texttt{altitude}
property, you should not modify its value directly. Instead, you invoke the methods \texttt{ascend()} and 
\texttt{descend()} to change its altitude because some actions need to be taken before climbing up or
going down, which are accounted for by the two methods. By interacting with methods through the interface,
the methods can check whether the operation is valid before committing any changes to the object. \\

Inheritance allows a class (subclass) to inherit methods from another class (superclass). For example,
a \texttt{Helicopter} class may inherit from the \texttt{Airplane} class the \texttt{ascend()} and \texttt{descend()}
methods, while adding a \texttt{stationary()} method which an airplane doesn't have and is a characteristic
of a helicopter. By inheriting from another class, you don't need to write the inherited code again (unless you
would like to override them). Inheritance allows creation of code that can be easily reused. \\

Polymorphism is a more abstract notion that cannot be easily explained without resorting to examples. The 
principle is that it allows programmers to use a consistent interface for method invocation on objects of different 
classes. \\ 

These concepts would be revisited later on. However, before we go further, let us write a simple Perl program 
with object-oriented perspective so that you can appreciate how an object-oriented program looks like in Perl. \\

\section{OOP Primer: Statistics}

In this section we write a simple Perl module \texttt{Stats.pm} which calculates the mean, variance and standard
deviation of a set of input numbers. We then write a perl program \texttt{stats.pl} which uses the module written to output these statistics
given the input of a set of numbers. The program listing is given first, and the theories are revisited afterwards. \\

\head{EXAMPLE}{Statistics Calculator}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/Stats.pm}
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/stats.pl}
\vspace{\baselineskip}

When the program is executed, the output looks like this: 

\begin{lstlisting}[backgroundcolor=\color{CodeBackground}]
cbkihong@cbkihong:~/docs/perltut/src/oop$ perl -w stats.pl

Statistics Calculator
Calculates several sets of statistics given a sequence of input numbers.

Enter one value on each line.
To exit, press Ctrl-C.
>> 13
>> 26
>>

Results ==============================
Number of values: 2
Total: 39
Mean: 19.5
Standard Deviation: 6.5
Variance: 42.25
\end{lstlisting} 


In this transcript, \mono{13} and \mono{26} were input and then Ctrl-C was pressed to signal the end of input list.
The results are then displayed. This program catches (intercepts) the SIGINT signal, which is generated when you press 
Ctrl-C. By default, if you press Ctrl-C when a program is running it promptly terminates the program. In this program,
I demonstrated how to install a \term{signal handler}, which is a subroutine that is automatically invoked when the 
corresponding signal is caught. The signal handler is executed instead of terminating the program. \\

\term{Signals} are messages sent by the operating system to a process (a program in execution). Because signal is a
notion from Unix, and the message broadcasting mechanism is different on every operating system, behaviour of signal
handling is platform-specific. Signals are readily supported on Unix platforms by using the signal handling system 
calls. Windows has limited support of signals. Support for common signals like SIGINT seems to be working on Windows,
though. The example program works on both of my testing platforms, namely GNU/Linux and Activestate Perl 5.8.0 on Windows. 
I chose to use signal because catching of the SIGINT signal and executing the \mono{getResults()} subroutine is handled
automatically so we don't need to place any extra code in the \mono{while} loop to detect the end of input list.
However, because an explanation of signals is out of the scope of this tutorial, and is not the main theme of this
chapter, my discussion of signals will stop here. \\

\subsection{Creating and Using A Perl Class}

Perl does not have any specialized syntax for classes as in many other object-oriented programming languages like
C++, Java and PHP. That makes OOP in Perl looks more cryptic than it really is. A Perl class is contained in a file
of extension `.pm' in its own package. This is called a \term{module}. The filename of the module is the name of the
class followed by `.pm'. The package name is also the name of the class. Recall from the previous chapter that if 
the package name contains \mono{`::'}, it is changed to the directory separator as the pathname when the module is being sourced.
The following table displays some example package names and the corresponding locations where they need to be saved. \\

\begin{table}[htbp]
\begin{center}
\begin{tabular}{ll}
\hline
\textbf{Package Name}	&	\textbf{File Path (relative to \mono{@INC})}	\\
\hline 
	\texttt{Stats}	&	Stats.pm \br \\
	\texttt{Crypt::CBC}	&	Crypt/CBC.pm \br \\
\hline
\end{tabular}
\end{center}
\caption{Relationship of Package Names and File Placements}\label{tab:perlmod}
\end{table}

Recall that \mono{@INC} contains a list of path prefixes that Perl uses to locate a Perl source file. 
A module contains all method definitions. Don't forget to put the \mono{1;} at the end of the module. 
Omitting this results in a compile-time error. \\

Before you use a module you should first import it into your program. You can use \mono{require} that you were
taught in Chapter~\ref{chap:scope}. You may import a module in one of two ways. The first way is to pass the
path to the module (relative to \mono{@INC}) in quotes to the \mono{require} function. For example, 
\mono{require "Crypt/CBC.pm";} Another way is to just specify the package name without quotes, for example
\mono{require Crypt::CBC;} However, the \mono{use} function is preferred in general for Perl modules.
The syntax of \mono{use} is \\

\texttt{
\textbf{use} MODULE \textcolor{optionalargs}{[LIST]};
} \\

It is semantically equivalent to \\

\begin{verbatimtab}[4]
BEGIN {
	require MODULE;
	import MODULE LIST;		# indirect object syntax
}
\end{verbatimtab}

which not only imports the module \mono{MODULE} at compile time, it also imports the symbols specified by \mono{LIST} into the 
current namespace (package) using the \mono{import} class method. \mono{import} is a special class method that may be defined by a class author. 
Many modules do not have any symbols to be exported, however, some of them do. If the method cannot be found, it is silently bypassed. For
example, users of the \mono{CGI::Carp} module may import from it the \mono{fatalsToBrowser} symbol, which is
actually the name of a subroutine that generates a page in HTML describing the details when an error 
occurs, which is then returned to the viewer's browser. This is used by CGI scripts to easily trap runtime errors.
The \mono{use} statement required is \\

\begin{verbatim}
use CGI::Carp 'fatalsToBrowser';
\end{verbatim}

Documentation of a class should tell you how to \mono{use} it, and whether any symbols need to be imported. Therefore,
usually you don't have to worry about this at all, unless you have to write a class that exports symbols. 
The \mono{use} function is generally preferred to \mono{require} because modules are imported at compile time.
Therefore, missing modules are discovered at the time the program is compiled before execution, which saves you
from an embarrassing situation where execution is on midway when Perl finds out some of the modules are missing
and the program fails to continue. \\

\subsection{How A Class Is Instantiated}

As mentioned previously, to instantiate a class is to create an object that belongs to the class. From the
\link{http://www.perldoc.com/perl5.8.0/pod/perlobj.html}{perlobj} manpage, a Perl object created is 
\textit{simply a reference that happens to know which class it belongs to}. How does everything fit together? \\

Let us go back to the \mono{new()} class method of the Stats class in our example. The most important 
statement is on line 12, that is, the \mono{bless()} statement. The \mono{bless()} statement makes the
reference \mono{\$this} no longer just an ordinary hash reference. It becomes an object reference of the
\mono{Stats} class, and by doing so you can also access the methods from the reference. Therefore, this 
method is known as a \term{constructor}, because it is where the object is created. A constructor is not 
necessarily called `\mono{new()}'. It can be of any name, despite it is customarily called \mono{new}. 
Object-specific data, or properties, are stored into the object reference. Let us explain each line one by one. \\

% magic wand bless
% Perl object is a bless()ed reference

\begin{lstlisting}[backgroundcolor=\color{CodeBackground},numbers=none]
my $arg0 = $_[0];
my $cls = ref($arg0) || $arg0;
\end{lstlisting}
\vspace{\baselineskip}

In Perl, methods are exactly identical in behaviour to subroutines. However, whether it acts like a method 
or a plain subroutine is determined solely by the way it is invoked. A method is a subroutine that expects
an object reference as its first argument. Using the \mono{new()} method as an example, the following ways 
of invoking it are identical: \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground},numbers=none]
my $obj = new Stats;			# Indirect object syntax
my $obj = Stats->new();			# C++-like class member invocation (recommended)
my $obj = Stats::new(Stats);	# Resembling subroutine invocation
\end{lstlisting}
\vspace{\baselineskip}

With the indirect object syntax, the name of the method is placed first, followed by the object reference or name
of the class. For example, \mono{getTotal \$obj ('a', 'b')} means that the method \mono{getTotal()} is invoked on the object
\mono{\$obj}. Any arguments that follow (\mono{'a', 'b'}) are arguments to the method. This form is generally 
only recommended for constructors, because this form of method invocation is not syntactically obvious. The second 
form is generally recommended as it's less confusing. The class name or object reference is placed first, followed 
by \mono{-\textgreater}, the method name and arguments. The last form is typical subroutine invocation. However, in this form
you need to pass the class name or object reference as the first argument. \\

Now go back to our example. We put the first argument to \mono{\$arg0}. The next line serves to obtain the class name
from it. The \mono{ref()} function tests if the parameter is a reference. If it is one, it returns a string indicating
its type (see the \link{http://www.perldoc.com/perl5.8.0/pod/func/ref.html}{ref()} documentation for details). 
If it is an object reference, it returns the package name. By the short-circuiting behaviour of logical operators 
the package name is assigned to \mono{\$cls}. This caters for the fact that the \mono{new()} method can be invoked
on the \mono{Stats} class or a class instance, although customarily, a constructor is only invoked on a class in most
other programming languages. \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground},numbers=none]
my $this = {};
bless $this, $cls;
\end{lstlisting}
\vspace{\baselineskip}

Here, we create an empty hash reference and \mono{bless()} it to the \mono{Stats} class. This operation is called
\mono{bless}, very likely because it works like a wizard playing with his magic wand, turning an ordinary reference 
into an object. Very magical indeed. To be an object, Perl only mandates a \mono{bless()}ed reference. It doesn't 
require to be a hash reference, although it is most likely chosen for its flexibility. Please read the 
\link{http://www.perldoc.com/perl5.8.0/pod/perltoot.html}{perltoot} manpage for its coverage on alternative forms
of Perl objects. It accepts two parameters. If the second parameter is missing, it assumes the current package. \\

The last two lines in the constructor resets the object data and return the object reference so that the
caller of the constructor (in stats.pl as \mono{\$obj}) can save the object reference for use in later operations. \\

The program reads in a number from each line, and invoke the \mono{addValue()} method on \mono{\$obj}. This invokes
the method with the object reference itself as the first parameter. The value, as the second parameter, is appended 
to a list of numbers that is stored with the object reference, and update the sum (\mono{x\_sum}) and the sum of 
squares (\mono{x2\_sum}). These two pieces of statistics are used to calculate the various statistics, when the SIGINT
signal is detected and the \mono{getResults()} signal handler invoked. The variance and standard deviation are given by \\

\begin{center}
Standard deviation ($\sigma$) $ \displaystyle = \frac{1}{n} \sqrt{(n \sum_{i=1}^n x_i^2 - (\sum_{i=1}^n x_i)^2)} $ \\
Variance $= \sigma^2 $ \\
%\[ \sum_{i=1}^n x \]
\end{center}

The class provides a number of methods for users of the class to retrieve the list of values, total, mean, variance
and standard deviation. Note that these methods are invoked on the \mono{bless}ed object returned by the constructor
instead of on the class. Through the class interface, the class provides all the necessary methods to
interact with without requiring the user to know anything about the implementation of the class. For example, you
do not have to care about how data are stored and processed internally. Because an object is simply represented by 
a reference variable, unlike some other programming languages Perl does not have the notion of protected access 
specifiers to classify methods by different access permissions such as ``public'' or ``private''. Users may also
be possible to manipulate the underlying hash directly. However, by documenting the interface clearly class 
users will be encouraged to access the object through the interface instead of having to manipulate object
data directly from the reference variable. This fulfills the initiative of encapsulation. \\

\section{Inheritance}

Inheritance is important in any programming languages because it allows you to reuse portions of another
source program in your program, so that you don't have to rewrite them. You save development effort as a result.
Perl implements inheritance in a very simple way. When a method is invoked on an object and the method cannot 
be found in the current package, the packages whose names are in the variable \mono{@ISA} are searched in order for
the missing method. In object-oriented terminology, we describe this situation as a \term{derived class} inheriting 
from a \term{base class}, because the derived class contains methods defined in itself as well as from the base 
classes. A base class is also called a \term{superclass} or a \term{generic class}, while a derived class is also
called a \term{subclass}. \\

When you put the name of a package into your package's \mono{@ISA}, all the methods defined in that package, together
with any defined in their base classes as well as the base classes of base classes etc. are available in your package.
You may wish to redefine some of the inherited methods because they may not suit your current class anymore. To 
redefine a method, which is called \term{overriding} a method, simply rewrite the method in the way you desire and
put it in the current package. If the method is invoked on the current package or its subclasses, the overriding method
will be invoked instead of the overridden ones (that is, those in the base classes). \\

% TODO: use base 'classname'

As an example, we will write a \mono{Stats2} class which inherits from \mono{Stats} with the added functionality
of deducing the maximum and minimum among the list of numbers input. Also attached below is the modified \mono{stats2.pl}
which \mono{use}s \mono{Stats2} with the additional functionalities: \\

\head{EXAMPLE}{Statistics Calculator (Extended)}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/Stats2.pm}
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/stats2.pl}
\vspace{\baselineskip}

Note that by placing the name of a package in \mono{@ISA} does not free you from the need of adding the 
\mono{use} statement to import the contents of the package. \mono{Stats} is the base class while \mono{Stats2}
is the derived class. Here, the \mono{addValue()} method is overridden
to check whether the current input number is the minimum or maximum and update the counters internally if 
it is one to always keep track of the minimum and the maximum. Then, two new methods are defined that let
users retrieve the minimum and maximum values. \\

Occasionally an overriding method needs to invoke an inherited but overridden method. \mono{addValue()} here
is an example, because we overrode it to add new functionalities rather than to replace it in its entirety. 
You can prefix a package name before the name of the method, separated by two colons, to indicate the class
from which to start searching for the method. The default is always to start searching from the package to which
an object belongs. Therefore, you always have access to the current, overriding version. You can access the
version defined in the \mono{Stats} package, that is the base class with respect to \mono{Stats2}, by \\

\begin{verbatim}
$this->Stats::addValue($num);
\end{verbatim}

However, for convenience a pseudo class \mono{SUPER} has been defined that always refer to the base classes.
Essentially, the current, overriding version is bypassed, as indicated in the example program. \\

The \mono{Stats2} class can actually make use of the \mono{getValueList()} method to deduce the maximum and
the minimum values on-the-fly instead of having to memorize two additional pieces of information, and the 
\mono{addValue()} method does not need to be overridden as a result. This is left as an exercise for the readers. \\

Even if your class's \mono{@ISA} is empty, it still inherits from a class called \mono{UNIVERSAL}, which is the
base class of all classes in Perl. Therefore, methods defined in \mono{UNIVERSAL} are available in any class.
It has three methods, which are described below. \\

\textbf{\mono{isa(CLASS)}} \\

This method allows you to check whether an object belongs to \mono{CLASS} or a subclass of \mono{CLASS}. It returns
a true value if it is one, \mono{undef} otherwise. You may use it in two ways. \\

Object-oriented form: \\
\begin{verbatim}
$obj->isa('UNIVERSAL');     # must be true, by definition
\end{verbatim}

Procedural form: \\
\begin{verbatim}
use UNIVERSAL 'isa';
isa($obj, 'UNIVERSAL');

\end{verbatim}

\textbf{\mono{can(METHOD)}} \\

This method allows you to check whether an object has a method called \mono{METHOD}. It returns
the reference to the subroutine if there is one, \mono{undef} otherwise. It also searches the upstream
base classes. As an example, this is an indirect and silly way to invoke the \mono{isa} method on the
current package: \\

\begin{verbatimtab}[4]
sub isSubclass {
	my ($this, $cls) = @_;
	my $subref = $this->can('isa');
	$this->$subref($cls);
}

$obj->isSubclass('UNIVERSAL');
\end{verbatimtab}

Can you add methods to a package like \mono{UNIVERSAL} without modifying the module file? The answer
is you can. Here, I am going to demonstrate how to add to the \mono{UNIVERSAL} class a constructor so that you don't 
have to define any constructors in your modules. \\


\head{EXAMPLE}{}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/universal.pl}
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/TestObject.pm}
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/testuniversal.pl}
\vspace{\baselineskip}

\mono{universal.pl} contains the methods to add to the \mono{UNIVERSAL} class. This file is sourced by a \mono{BEGIN}
block in \mono{testuniversal.pl} which ensures that the module definitions are imported at compile time. Note that the
\mono{TestObject} module does not have to define the constructors as a result. Note that you may optionally specify an 
\mono{initialize()} method in your class module, which is automatically invoked by the constructor (\mono{universal.pl}::9)
where you can place some initialization code. If you do not provide it, the version provided by \mono{universal.pl}
will be used instead, which is just an empty method that does not do anything. \\

Although you may do it that does not necessarily mean you should do it. In general, I suggest converting \mono{universal.pl}
into a module which acts as the base class for all your other modules instead of adding new methods to the \mono{UNIVERSAL}
class. This example is given to demonstrate it works. However, if a user of \mono{TestObject} forgets to import the
\mono{universal.pl}, then it will be an error as a constructor cannot be found. \\

\begin{comment} % XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

\section{Another Example: Traffic Light Simulation}

If my discussion in the previous section definitions sounds too abstract to you, let us consider a fictitious TrafficLight 
class which models a typical traffic light we have on the streets today. We would write a program which
models its behaviour in a strict object-oriented approach so that you can appreciate OOP in a practical
context. \\

For simplicity, let's assume the traffic light consists of two states only. A red light denotes ``stop''
and a green light denotes ``go''. The two states are mutually exclusive, that is, exactly one of the
two lights should be lit at any time. The state alternates every 10 seconds. This is coordinated by 
a controller regulated by a timer. \\

This situation can be modeled using three classes, because three types of objects exist, namely the 
traffic light, the controller and a timer. The three objects have different behaviours, so we separate 
the program into three classes. Each TrafficLight object only needs to remember one piece of information,
that is, the current state, in order to (logically) switch on the appropriate light bulb. As different traffic
lights can be in different states at any given instant, the state can be regarded as a property 
associated with each TrafficLight object. To change the state of the TrafficLight we can create
a \texttt{state()} subroutine and associate it with the TrafficLight class through which
the state of the TrafficLight object concerned can be retrieved or set. A Timer object implements 
a countdown timer to regulate the controller, which in turn invokes the change
in the state of the traffic light. \\

While I have not yet covered how to write a Perl program in object-oriented approach, I consider it
may be helpful for me to show the source code early so that you can have some more practical ideas of 
object-oriented programming and how OOP is implemented in Perl. Note that OOP in Perl makes extensive
use of references, which are not introduced until the next chapter. You are encouraged to flip to the
next chapter to get some basic ideas of references first. Alternatively, the source code is extensively
commented so that you can try to appreciate the program structure without fully understanding the 
syntax. I will explain what the program does and how everything fits together as I proceed. \\

\head{EXAMPLE}{}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/Timer.pm}
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/TrafficLight.pm}
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/Controller.pm}
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/oop/tlight1.pl}


Class modules carry the ``.pm'' file extension. Among the four source file listings above, the first 
three are Perl class modules, representing the classes \texttt{Timer}, \texttt{TrafficLight} and 
\texttt{Controller} respectively. The last listing, \texttt{tlight1.pl} is the main program that 
uses the Perl classes developed to carry out the required functionality. You will find that if a 
program is developed entirely with the object-oriented paradigm the main program is usually 
short because implementations are delegated to modules. \\

On lines 5-6 of \texttt{tlight1.pl}, we import the classes needed. In the next section, we would see that
\texttt{use()} is a wrapper of \texttt{require()} which is usually the preferred way of importing modules
so that they can be used thereafter in the program. Then we create one object of \texttt{TrafficLight} 
and \texttt{Controller} respectively. After associating the \texttt{TrafficLight} object with the 
\texttt{Controller} object, what is left to do is to invoke the \texttt{start()} method of the 
\texttt{Controller} object. \\

On execution you would then see messages printed at regular intervals, corresponding to the colour 
of the traffic light at that instant. The colours keep on alternating and to quit this program you
need to press Ctrl-C. \\

\end{comment} % XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

\section*{Summary}

\begin{summary}
\item Object-oriented programming refers to the practice of grouping related subroutines and data into a self-contained logical entity, called a class. 
\item Each class defines a framework which describes the set of behaviours and properties of objects instantiated from the class.
\item Methods are subroutines associated with the class. Properties are attributes possessed by objects instantiated from the class.
\item Encapsulation refers to the practice of hiding internal class implementation from users. Class users are expected to only interact with it through public methods.
\item Inheritance allows a subclass to inherit methods from a superclass, so that you may save development effort through reuse.
\item A class module in Perl is simply a package, whose file extension is `.pm'. 
\item The \mono{use()} function is usually used to load a Perl module at compile time.
\item Every Perl class has a constructor which is responsible for creating objects belonging to the class.
\item The \mono{bless()} function associates a reference variable with a class in order for the reference to become an object.
\item A method inherited from a superclass may be overridden by specifying the definition for the subclass.
\item In class methods the \mono{SUPER} pseudo class may be used to invoke an overridden method. 
\item All classes inherit a class named \mono{UNIVERSAL}.
\end{summary}

\section*{Web Links}

\begin{list}{\thechapter.\arabic{count}}{\usecounter{count}}
\item {
	\link{http://www.perldoc.com/perl5.8.0/pod/perlboot.html}{perlboot manpage --- Object-Oriented Tutorial for Beginners} \\
	\textit{http://www.perldoc.com/perl5.8.0/pod/perlboot.html}
}
\item {
	\link{http://www.perldoc.com/perl5.8.0/pod/perltoot.html}{perltoot manpage --- Tom's Object-Oriented Tutorial for Perl} \\
	\textit{http://www.perldoc.com/perl5.8.0/pod/perltoot.html}
}
\item {
	\link{http://www.perldoc.com/perl5.8.0/pod/perltooc.html}{perltooc manpage --- Tom's Object-Oriented Tutorial for Class Data in Perl} \\
	\textit{http://www.perldoc.com/perl5.8.0/pod/perltooc.html}
}
\item {
	\link{http://www.perldoc.com/perl5.8.0/pod/perlbot.html}{perlbot manpage --- Object-Oriented Bag of Tricks} \\
	\textit{http://www.perldoc.com/perl5.8.0/pod/perlbot.html}
}
\end{list}
