News for hackers. Stuff that matters.
Re:Ask HN: Why do you make class members private? by alkonaut on Monday July 25, 2022 @02:22PM (#32228697)
If the exposed data is (and will always be) the same as the stored data, and the data is immutable - then you are right there is little point.

If the field is mutable then obviously you may want to keep it private to ensure some invariant, or to cache/invalidate/log something when accessed. Accessing the private data directly will circumvent that.

If the exposed data isn’t the same as the stored data (e.g a DateTime struct might have a field with a 32 bit Unix timestamp but only exposes year/month/day/hour…). The reason for not exposing it because you don’t want consumers to depend on it. If you changed to a 64 bit internal representation you will break any consumer who is using the private field. But if you only expose year/month/day/hour/… then you can solve your year-2038-problem by simply changing the data type. Anything exposed is depended on. Always. And here is the kicker: it doesn’t matter if your consumers are other classes in the same program, or library users for a shipped api, they are users and they will (mis)use your class in any way possible. In the library api case you break others’ code. In the internal code case you might get a missed cache, or a harder refactor or similar.

There are no comments on this comment yet.