Private vs. Public members in practice (how important is encapsulation?)

Posted by Asmor on Stack Overflow See other posts from Stack Overflow or by Asmor
Published on 2008-09-19T04:44:32Z Indexed on 2010/05/09 10:58 UTC
Read the original article Hit count: 116

One of the biggest advantages of object-oriented programming is encapsulation, and one of the "truths" we've (or, at least, I've) been taught is that members should always be made private and made available via accessor and mutator methods, thus ensuring the ability to verify and validate the changes.

I'm curious, though, how important this really is in practice. In particular, if you've got a more complicated member (such as a collection), it can be very tempting to just make it public rather than make a bunch of methods to get the collection's keys, add/remove items from the collection, etc.

Do you follow the rule in general? Does your answer change depending on whether it's code written for yourself vs. to be used by others? Are there more subtle reasons I'm missing for this obfuscation?

© Stack Overflow or respective owner

Related posts about best-practices

Related posts about encapsulation