Search code examples
coopencapsulationsoftware-design

Bob Martin: "C has perfect encapsulation" HOW?


Bob Martin in this video says that "C has perfect encapsulation". I do not understand why he is saying this... I understand that we can separate the implementation in a .c file and declare the interface in a header .h file, but there is nothing really stopping me from accessing implementation details like this:

main.c

#include <stdio.h>
#include "file1.h"
extern int x;
int main() {
    printf("%d\n", x);
    return 0;
}

file1.c

int x = 5;

int getnum_file1() {
    return x + 1;
}

file1.h

int getnum_file1();

In this case, main.c has access to implementation detail in file1.c. This code also compiles and executes with the expected result. How is this perfect encapsulation??


Solution

  • A way to ensure the encapsulation is declaring x as static int x = 5;, so it won't be visible from an external object (even using extern).

    Obviously, a global variable as x is, can be accessed from another object (via linker, through the extern you have added). However, this usually leads to a "spaghetti" code, in which variables are accessed and/or modified from wherever because there is not a proper encapsulation (and C or C++ do provide useful ways to avoid that).