|go ahead... be a heretic|
Re^4: Why encapsulation mattersby Ovid (Cardinal)
|on May 19, 2008 at 08:20 UTC||Need Help??|
The problem I generally have with OO is that most people don't know it and then they get frustrated (and rightly so). This is because it's not being taught very well and I certainly had painful experiences with it when I started. That being said, I can't say I disagree with your post, but I can't agree with it, either, because I don't understand what you're trying to say. I guess I work better with examples :)
My argument goes like this: expose nothing.
Pretty simple, eh? If the class should be responsible for something, others should not know or care how the class does it. This is even more important if exposing those details allows code outside the class to put an instance (or worse, the class itself) into an invalid state. By pulling logic outside of the class, this risk increases. For example:
That if/else is a bug waiting to bite. It only takes one absent-minded programmer to forget an if/else block there and then life becomes pain for everyone.
The authenticate method should probably be throwing its own exception and the calling code, if it cares, should catch it. By not doing this, it's much easier for the calling code to forget to check the return status of that method. Forcing the consumer of a module to write extra code is a recipe for bugs. Here's a somewhat better way:
Because authenticate throws its own exception, you can't reach the offending code unless you authenticate (i.e., forgetting an if/else block doesn't matter) and the code is easier to read. You can't forget to check the return code (unless you explicitly have a block eval and don't check $@).
So the point I am making is not "shove everything inside of the class". It's "expose nothing until you know you need to expose it". I've found that this has worked very, very well in managing larger code bases.