Sunday 4 December 2016

Opaque data types

Data types are tools to describe data. But to whom is this description meant for? One would assume that since a programmer is writing the data type, it is meant for the programmer. But there are cases when the data type written by one programmer is made available to another without the source or any knowledge of what the data type contains. What the later is provided with are some guidelines of how and when to use the instances of that data type. The only thing allowed is for someone to pass the objects of the data type around without ever touching the internals of it. Such data types are called opaque for literal reasons.
One example of opaque data types that is given in abundance is that of the FILE structure in C. The argument goes that since we never do things like:

FILE *obj;
obj.some_member = some_value;

We can say that this is opaque. This is true by definition if no one is made aware of the structure of this struct. And if we are not made aware of the structure then we can't access the members, simply because we won't know what the members are. All we can do is use the objects or pointers to the objects and pass them around to functions that know how to manipulate these. Examples of such functions would be fopen and fclose in the C language that are used to work with FILE structure pointers.

This implies that since such functions can manipulate these structures, they must know what the structures contains and hence these functions must also be made opaque from the user programmer otherwise he/ she could just look these functions up and code a similar one based on the knowledge of the internals of the structure. This is not like the creators of such types don't want us to see what they have done. It is because we don't want to know what is inside. Each data type is there for a purpose and the purpose of opaque data types is realised completely with the APIs provided to use them. Extending its internals to the programmer will do no good and may even prove to be counter productive.

Think of the opaque data types as black boxes that are too important for one to open up and play around with. They are meant to be played with as is i.e. like a black box. It is not as if the internals of such types are an absolute secret. It depends entirely on the people implementing the library that is providing these. Some chose to provide the source, others just offer the binary. Any which way, the internals of the structure are not intended for use in a program hence they shouldn't matter whether they are available or not.

No comments:

Post a Comment