Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: [Caml-list] OO design
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: yoann padioleau <padator@w...>
Subject: Re: [Caml-list] OO design

 
> Which brings us to a question : how do you enforce protocols in OCaml ?
> 
> Say, is there a "good" way of rewriting file-related operations so that, say, 
> ProtocolUnix.read and ProtocolUnix.write *statically* only accept opened 
> files, and in addition, ProtocolUnix.write only accepts files which have been 
> opened with write priviledges ?

Have different types,  in_channel  and out_channel. But ocaml already have this.
The problem is that when you close a channel, ocaml does not warn you
if you try to read from a close channel.

> 
> I mean, there are manners of checking this with, say, model checking tools. In 
> the specific case of file management, I guess we can do it with a little bit 
> of simple subclassing, but I assume there's a large run-time penalty for this 
> extra bit of checking, due to the management of objects by OCaml. Has anyone 
> attempted to determine how well this scales up ? Or explored other options ?

Using higher order functions.
Instead of having a  open/read/close sequence protocol that you must follow, 
enforce such a protocol by defining a higher order function let's say
with_open_out_file that do all that for you under the hood.


with_open_out_file "/tmp/test.txt" (fun write_func -> 
 (* you can call write_func that do the writing *)
  write_func "toto";
  write_func "titi";
 );
 


let with_open_out_file file f = 
 let chan = open_out file in
 let read_func = output_string chan in

  try (
   f read_func;
   close_out chan;
  ) 
 with 
  x -> close_out chan; raise x


Note how the channel is automatically closed for you. 


This technique is used in Lisp library I think.