Version française
Home     About     Download     Resources     Contact us    
Browse thread
about "new"
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Didier.Remy@i...
Subject: Re: about "new"
>  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.