Chapter 5 |
Advanced examples with classes and modules |
|
(Chapter written by Didier Rémy)
In this chapter, we show some larger examples using objects, classes
and modules. We review many of the object features simultaneously on
the example of a bank account. We show how modules taken from the
standard library can be expressed as classes. Lastly, we describe a
programming pattern know of as virtual types through the example
of window managers.
5.1 |
Extended example: bank accounts |
|
In this section, we illustrate most aspects of Object and inheritance
by refining, debugging, and specializing the following
initial naive definition of a simple bank account. (We reuse the
module Euro defined at the end of chapter 3.)
#let euro = new Euro.c;;
val euro : float -> Euro.c = <fun>
#let zero = euro 0.;;
val zero : Euro.c = <obj>
#let neg x = x#times (-1.);;
val neg : < times : float -> 'a; .. > -> 'a = <fun>
#class account =
object
val mutable balance = zero
method balance = balance
method deposit x = balance <- balance # plus x
method withdraw x =
if x#leq balance then (balance <- balance # plus (neg x); x) else zero
end;;
class account :
object
method balance : Euro.c
method deposit : Euro.c -> unit
method withdraw : Euro.c -> Euro.c
val mutable balance : Euro.c
end
#let c = new account in c # deposit (euro 100.); c # withdraw (euro 50.);;
- : Euro.c = <obj>
We now refine this definition with a method to compute interest.
#class account_with_interests =
object (self)
inherit account
method private interest = self # deposit (self # balance # times 0.03)
end;;
class account_with_interests :
object
method balance : Euro.c
method deposit : Euro.c -> unit
method private interest : unit
method withdraw : Euro.c -> Euro.c
val mutable balance : Euro.c
end
We make the method interest private, since clearly it should not be
called freely from the outside. Here, it is only made accessible to subclasses
that will manage monthly or yearly updates of the account.
We should soon fix a bug in the current definition: the deposit method can
be used for withdrawing money by depositing negative amounts. We can
fix this directly: