Hacker News new | ask | show | jobs
by haberman 371 days ago
Most data structures have invariants that must hold for the data structure to behave correctly. If users can directly read and write members, there's no way for the public APIs to guarantee that they will uphold their documented API behaviors.

Take something as simple as a vector (eg. std::vector in C++). If a user directly sets the size or capacity, the calls to methods like push_back() will behave incorrectly, or may even crash.

Opaque pointers are one way of hiding representation, but they also eliminate the possibility of inlining, unless LTO is in use. If you have members that need to be accessible in inline functions, it's impossible to use opaque pointers.

There is certainly a risk of "implicit interfaces" (Hyrum's Law), where users break even when you're changing the internals, but we can lessen the risk by encapsulating data structures as much as possible. There are other strategies for lessening this risk, like randomizing unspecified behaviors, so that people cannot take dependencies on behaviors that are not guaranteed.

1 comments

> Most data structures have invariants that must hold for the data structure to behave correctly. If users can directly read and write members, there's no way for the public APIs to guarantee that they will uphold their documented API behaviors.

You can, just not in the "strictly technical" sense. You add a "warranty void if these fields are touched" documentation string.

That's honestly horrible. It's like finding your job is guaranteed by a pinkie promise, or the equivalent.
Most of the world runs on a handshake.
That's not a valid argument. For most of human existence there was cannibalism and/or human sacrifices. This doesn't mean we should go back to it.
isn't that the norm in many places on earth?
I prefer liability when devs misuse software with consequences for society infrastructure.
A language adding private fields does not add liability.
Indeed, misusing the library and causing software faults does, so every stone in the way preventing misuse helps.