Encapsulation in C


  • 0

    Wait what?! Encapsulation in a procedural language?!
    With discipline, C has more than potent encapsulation!
    Let us consider an example:

    We have a queue of integers and a queue client. What is the queue client's view of the queue?
    To answer that we ask : "What is needed by the client to use the queue?" - Simply queue.h

    queue.h

    typedef struct queue * queue_t;
    void queue_add(queue_t q, int item);
    int queue_poll(queue_t q);
    

    That's it! There is no way for the client to know how the queue is implemented : linkedlist or array or any other implementation level detail. All it knows about is the queue's interface - the two function signatures defined in the header file and a pointer to the structure that is the queue! The queue implementation is perfectly abstracted and encapsulated away from any client in a separate file : queue.c.

    queue.c

    #include "queue.h"
    #define Q_INIT_CAPACITY 10
    struct queue {
    	//implementation-specific members
    	int items[Q_INIT_CAPACITY];
    };
    void queue_add(queue_t q, int item) {
    	//..
    }
    int queue_poll(queue_t q) {
    	//..
    }
    
    

    In a way, we use header files to define interfaces, much like interfaces you would define in say, Java. The function declarations/prototypes are analogous to Java abstract functions.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.