Information hiding in Erlang

Luke Gorrie <>
Fri Apr 28 12:00:30 CEST 2000


Jith Meganathan <> writes:

> I've attached a module I wrote implementing a simple priority queue with
> operations to add and pop elements, and to view the element with highest
> priority. The data structure used is a list of tuples, where each tuple
> contains an element and a priority. In writing the module, I felt a
> certain...nervousness at trusting callers to pass in a valid data
> structure each time they invoked a function in the module. Does Erlang
> provide mechanisms for encapsulating data structures, or is lack of
> information hiding just something to be accepted when programming a
> functional language?

You could make an abstract data type out of queue elements with:

qelement({Elt, _Priority})  -> Elt.
qpriority({_Elt, Priority}) -> Priority.

Since it's often useful to use these things as lists anyway, you could
also add:

%% Turn a Queue into an ordered list of {Element, Priority} and vice versa
queue_to_list(Queue) -> Queue.
list_to_queue(List)  -> List.

This should be sufficient to let you change the "internal" data
structure however you want in future. The "dict" module in stdlib
makes a good example, I think.

So, you still don't have compilier- or runtime- checks enforcing
encapsulation, but you do have a way to write clients which doesn't
rely on the format of the list.

Cheers,
Luke




More information about the erlang-questions mailing list