Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] Protected methods
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-07-20 (00:46)
From: Jacques Garrigue <garrigue@k...>
Subject: Re: [Caml-list] Protected methods
From: Alessandro Baretta <>
> > Actually, this seems perfectly practical.
> > If you have some good reason to "protect" a method, you can do it
> > cleanly.
> I would not call adding a fake type a clean solution. It's 
> not idiomatic. A "protected" keyword is cleaner and easier 
> to handle. Although it might be very tricky to implement in 
> a language with type inference.

Actually, this is just an alternative model for protection:
give all your clients the key, and don't give it to other people.
This makes sense. The key can be a dummy only because the type system
guarantees that you cannot forge its type.
The problem with a "protected" keyword is that it should be given a
semantics. Since an object type is structural (does not belong to a
specific module), this is unclear how you can define where a protected
method should be accessible.

In practice, I probably won't do it that way, but this would require a
deeper knowledge of your problem.
For instance, if you want to show an internal state to a limited
number of clients, you can just have a method returning this state
with an abstract type. That's certainly more natural.

> How about the following pseudocode? Is it sensible/viable?
> let module M : sig
>    class type public = object <public_methods> end
>    val make_public : unit -> public
> end = struct
>    class type public = object <public_methods> end
>    class protectd =
>      object (self : #public)
>      <public_methods>
>      <protected_methods>
>    end
>    let make_public () -> (new protected :> public)
> end
> If this a working alternative, I would prefer over both the 
> protector type and the protected keyword: clean, simple, and 
> idiomatic.

This is both sensible and viable.
The only weakness is that you won't be able to inherit from the public
version of your class, since it is not a class but only a type.
If you need to inherit, you should also export the protected version,
and make sure that all your constructors apply a similar coercion to
hide protected methods.

This inheritance problem is the only reason I didn't suggest this
approach first, but it is certainly simpler.

Jacques Garrigue
To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: