Thursday, November 20, 2008

Information Hiding in C programming language

Information Hiding in C
-----------------------------

Though C language doesn't fully support encapsulation as C++ does, there is a simple technique through which we can implement encapsulation in C. The technique that achieves this is modular programming in C. Modular programming requires a little extra work from the programmer, but pays for itself during maintenance. To understand this technique let us take the example of the popular stack data structure. There are many methods of implementing a stack (array, linked list, etc.). Information hiding teaches that users should be able to push and pop the stack's elements without knowing about the stack's implementation. A benefit of this sort of information hiding is that users don't have to change their code even if the implementation details change.

Consider the following scenario:
To be able to appreciate the benefits of modular programming and thereby information hiding, would first show a traditional implementation of the stack data structure using pointers and a linked list of structures. The main( ) function calls the push( ) and pop( ) functions.


#include 
typedef int element ;
void initialize_stack ( struct node ** ) ;
void push ( struct node **, element ) ;
element pop ( struct node * ) ;
int isempty ( struct node * ) ;
struct node
{
element data ;
struct node *next ;
} ;
void main( )
{
struct node *top ;
element num ;
initialize_stack ( &top ) ;
push ( &top, 10 ) ;
push ( &top, 20 ) ;
push ( &top, 30 ) ;
if ( isempty ( top ) )
printf ( "\nStack is empty" ) ;
else
{
num = pop ( top ) ;
printf ( "\n Popped %d", num ) ;
}
}
void initialize_stack ( struct node **p )
{
*p = NULL ;
}
void push ( struct node **p, element n )
{
struct node *r ;
r = ( struct node *) malloc ( sizeof ( struct node ) ) ;
r -> data = n ;
if ( *p == NULL )
r -> next = NULL ;
else
r -> next = *p ;
*p = r ;
}
element pop ( struct node *p )
{
element n ;
struct node *r ;
n = p -> data ;
r = p ;
p = p -> next ;
free ( r ) ;
return ( n ) ;
}
int isempty ( struct node *p )
{
if ( p == NULL )
return ( -1 ) ;
else
return ( 0 ) ;
}

Notice how the specific implementation of the data structure is strewn throughout main( ). main( ) must see the definition of the structure node to use the push( ), pop( ), and other stack functions. Thus the implementation is not hidden, but is mixed with the abstract operations.



No comments:

Blog List