P is for Practical | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Whether or not an accessor violates encapsulation depends upon the class. While there's a good argument that you should often just send messages to an object and let it decide how to respond rather than pull bits of data out of it, that's for objects that I see as modelling a process or need. A perfect example is this oft-repeated mistake:
With code like that, the programmer has to remember to check for an error every time she might need to log one. More stuff to remember means more bugs. Instead, push the $obj->error call into the &log_error method and let the object ignore the message if there are no errors (though even exposing the &log_error method may not be good.) However, sometimes a class can merely be viewed as a data type where you have fine-grained control over the domain of values the data can represent. I mean, I could create an integer variable which is only supposed to hold prime numbers. I could also create a Prime class which does the same thing but actually restricts me to prime numbers. In the latter case, my code may arguably be more correct but there's also nothing wrong with asking what the prime number is. As for whether or not you should only test your published API, people disagree about that, also. On the "purity" side, there are those who argue that only the published API should be tested as that's all you are promising. Plus, testing the internals means you're more likely to break tests as you refactor, add, or delete code. However, I do like to test the internals, though I will often keeps those tests separate. The reason I do this is the API is often like the tip of an iceberg. There's a whole lotta code underneath. While you definitely want to test the API (and probably test that first), if you have a lot of code that this doesn't test directly, you may find a bug but have a much harder time tracking it down. Internals testing means you quickly find what's really broken, though this can mean more maintenance down the road. Cheers, New address of my CGI Course. In reply to Re: "Accessors (don't always) break encapsulation"
by Ovid
|
|