Hacker News new | past | comments | ask | show | jobs | submit login

I'd have to politely disagree; if your class has mutable state and you want to maintain some invariant relationships amongst the elements of your class then as far as I can see you really need to be able to specify that some operations can only be performed within the class. If your class is immutable then I'd agree that in most cases privacy offers you few benefits.



Yes, that's the theory. In practice it doesn't seem to work out so well. Neither the promised benefits of using private fields actually manifest, nor the promised costs of not having private fields, but the costs of actually having the private fields manifest in spades. In cost/benefits terms, the benefits are almost entirely theoretical and the costs much higher than advertised. I consider them a major net loss for OO.


I wouldn't really agree that it doesn't work out in practice. For the systems that I work on, the concept of privacy is extremely useful, perhaps we're doing things 'the wrong way' to believe that but I don't think that's all that likely.

What would you suggest as a better alternative, outside of a purely functional approach? Just as an example, suppose that Java's LinkedList class didn't have a cached size and that instead it went and iterated its elements to calculate its size each time someone asked for it. I might write a wrapper around LinkedList with two private variables, the LinkedList and an int to cache its size in. Then I would update the int each time an operation was performed on my member list. If I can't make those two members private, how can I ensure that no one accidentally updates the list without updating the size, or vice-versa. It mightn't be an unreasonable mistake for someone to think calling mylist.size = 0 would empty the list. What is the 'safe' way of constructing this concept?


> If I can't make those two members private, how can I ensure that no one accidentally updates the list without updating the size, or vice-versa. It mightn't be an unreasonable mistake for someone to think calling mylist.size = 0 would empty the list. What is the 'safe' way of constructing this concept?

Conventions. In Python, for instance, all private fields and methods start with a double underscore, i.e., '__'. This is merely a convention, outlined in PEP8. Documentation tools don't pick up "private" fields. Even when they do, they don't list them in the same section as the public fields.

You could argue about the safety of this approach, but at some point you have to let go of the training wheels and let programmers make their own judgments.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: