in reply to Re^3: Make everything an object?
in thread Make everything an object?
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:
my $auth = Authentication::Manager->new( { store => $store } ); if ( $auth->authenticate($username, $password) ) { delete_the_data_store($store); } else { throw_some_exception "invalid credentials"; }
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:
my $auth = Authentication::Manager->new( { store => $store } ); $auth->authenticate($username, $password); delete_the_data_store($store);
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.
Cheers,
Ovid
New address of my CGI Course.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: Why encapsulation matters
by BrowserUk (Patriarch) on May 19, 2008 at 09:30 UTC | |
by Ovid (Cardinal) on May 19, 2008 at 12:48 UTC | |
by Ovid (Cardinal) on May 19, 2008 at 13:23 UTC | |
by BrowserUk (Patriarch) on May 19, 2008 at 22:49 UTC | |
by Ovid (Cardinal) on May 20, 2008 at 06:04 UTC | |
by BrowserUk (Patriarch) on May 20, 2008 at 08:15 UTC | |
|