Thursday, August 30, 2018

A Quick Exploration of Encapsulation

A long time ago, I had an argument about C++ with a coworker. He said that a private field could not be accessed in C++ because that's how the language works. I argued that it could because it was all just bits in memory.

He was adamant in his assertion and the only way to win the argument was to write a little patch of code that took a pointer to an object, converted that to a void* pointer, converted that to a char array, and then poked bytes into a private field using the char array.

This argument is emblematic of what encapsulation does and doesn't do for us.

Encapsulation is not about making it impossible for someone to do the wrong thing. It's about making it extremely improbably that they would create inappropriate coupling on accident.

This is always true. A determined developer with write-access to your code can get to anything they desire; fields, classes, libraries...nothing is safe if they have malicious intent.

Fortunately, most bad coding decisions are made absent mens rea. It's okay that you basically can't prepare your code for ill will because it usually doesn't happen. The rare occasion when it does is a security issue, not a coding problem.

Ultimately, encapsulation is primarily a technique we use to minimize undesirable coupling. Anything you do that makes it harder to couple to something accidentally, needlessly, or subtly, is a form of encapsulation.

You can encapsulate anything you want to hide and most developers will respect that. Developers who are acting in conscientious ignorance will promote the visibility of something that should be hidden and you will have a chance to catch them.