Re: about "new"

Didier Remy (Didier.Remy@inria.fr)
Fri, 25 Jul 1997 13:54:36 +0200 (MET DST)

Message-Id: <199707251154.NAA14258@pauillac.inria.fr>
Subject: Re: about "new"
In-Reply-To: <33D86D30.5889@labri.u-bordeaux.fr> from Pierre CASTERAN at "Jul 25, 97 11:09:04 am"
To: Pierre.Casteran@labri.u-bordeaux.fr (Pierre CASTERAN)
Date: Fri, 25 Jul 1997 13:54:36 +0200 (MET DST)
From: Didier.Remy@inria.fr (Didier Remy)

> I'm a beginner in Objective Caml, but not in ML; my question is about
> object building :
> Is there any way to define a class with some initializing function,
> which is to be called each time an instance is created by a "new" ;
> the interest would be of course to create a "consistent" state for
> a newly created object.

There are no such things as initialization methods defined in classes to
create new objects.

The only way to create an object from a class is the "new" construct.
You can always guarantee consistency by defining your own creation function.
For instance, assume you have defined the a class of integer values

class integer x as self =
val repr = x
method incr = {< repr = repr + 1 >}
method print = print_int repr
end;;

and that you want to ensure that repr is always positive.
You may defined

let real_integer x =
if x > 0 then new integer x
else raise (Failure "negative")
;;

and use real_integer x instead of new integer x to create integer objects.

real_integer 1;;
real_integer 0;;

However, consistency checks being written outside of classes will not
be inherited that way. A better solution is then to put them inside the
class.

class real_integer x =
inherit integer x
val repr = if x > 0 then x else raise (Failure "negative")
end;;

new real_integer 1;;
new real_integer 0;;

They will be inherited.
However, this way they is a unique view of security.
You need several subclass to implement several views of security.
Another possible solution is to add methods for checking consistency:

class real_integer x as self =
inherit integer x
method check =
if repr > 0 then self else raise (Failure "negative")
end;;

(new real_integer 1)#check;;
(new real_integer 0)#check;;

This allows several checks, but make consistency checking visible methods
of the object. This can be hidden a posteriori:

let real_integer x = ((new real_integer x)#check : integer);;
real_integer 1;;
real_integer 0;;

Hope this helps,

--Didier.