On 2011/08/27, at 19:53, Chris Yocum wrote:

> A friend of mine is giving a talk about "monkey patching" entitled
> "Monkey patching, subclassing, and accidental overriding"
> (http://aaroncrane.co.uk/talks/monkey_patching_subclassing/paper.html).
> I was wondering how Ocaml deals with this situation or if it is even a
> problem at all in Ocaml?  I mocked up some code:
> 
> class base =
> object
>  method meth x =
>    print_endline "base";
>    print_endline (string_of_int x)
> end
> 
> class deriv =
> object
>  inherit base
>  method meth x =
>    print_endline "deriv";
>    print_endline (string_of_int x)
> end
> 
> which kind of(?) shows the problem in Ocaml.  He suggests in his paper
> that using a Meta-Object Protocol is the way around this.  What do you
> think?


You can require overriding to be explicit by activating warning 7:

$ ocaml -w +7
        OCaml version 3.13.0+dev6 (2011-07-29)

# class c = object method x = 1 end;;
class c : object method x : int end
# class d = object inherit c method x = 2 end;;
Warning 7: the method x is overridden.
class d : object method x : int end

Note also that in ocaml a method only has one signature,
so the problems with API changes doesn't apply here:
you get an error if the type changed in the base class,
and a warning if the method name was changed in the base class.

However, in this respect I think that a "final" keyword is missing in ocaml.
Namely, you have no way to say that you don't want subclasses to modify
a method (because you want to be able to redefine it yourself, for instance).
But OCaml is not an object-only language, so if you want this kind of
guarantee you can use functors: specify exactly what the user should provide,
without allowing a posteriori overriding.

Jacques Garrigue

-- 
Caml-list mailing list.  Subscription management and archives:
https://sympa-roc.inria.fr/wws/info/caml-list
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs

Reply via email to