Search code examples
cencapsulation

In the context of “encapsulation”, what is meant by the phrase “protecting objects from unwanted accesses by a client”


In Chapter 19 of “C Programming: A Modern Approach”, the idea of encapsulation (although ‘meager’ in C programming language) is introduced.

As motivation for implementation of encapsulation, the author alludes to the importance of protecting objects from being accessed by clients. Comments about avoiding the “corruption” of data fields within structures are referenced.

Perhaps because I am still quite a novice in software development in general (I’ve only ever written small programs...with a few .h and .c files), I don’t really understand the necessity of “protecting objects”.

Ultimately, doesn’t the programmer (with explicit code) dictate whether or not an object is directly accessed? It’s not like the compiler will “accidentally” access a structure and modify members, right?

From my understanding, the “corrupting access” would only occur if there was an explicit piece of code that said “access that structure and alter the data”...and presumably the piece of code responsible for initiating that action was user-generated.

Thus, is the only purpose of encapsulation to protect the “purpose of program” from user-errors incurred throughout the actual programming process?

Thanks!


Solution

  • From my understanding, the “corrupting access” would only occur if there was an explicit piece of code that said “access that structure and alter the data”...and presumably the piece of code responsible for initiating that action was user-generated.

    Yes, and that is exactly the problem. If users can access internal structs / objects / whatever, there is a non-zero chance that they will. If you know some internal object is not useful for end-users, why not prevent them from accessing it? That way you can guarantee that your library works as intended, because its internal structure or objects were only modified by code that you wrote yourself.

    Perhaps because I am still quite a novice in software development in general (I’ve only ever written small programs...with a few .h and .c files), I don’t really understand the necessity of “protecting objects”.

    Ultimately, doesn’t the programmer (with explicit code) dictate whether or not an object is directly accessed? It’s not like the compiler will “accidentally” access a structure and modify members, right?

    If you didn't restrict access to internals, you are placing the responsibility of keeping the internal objects correct on the end user. For large libraries, this can be quite difficult to manage. Again, restricting access to things a user doesn't need to access is a way to absolve them of responsibilty and to prevent errors.