Just another Perl shrine | |
PerlMonks |
Re: Inheritance vs Delegation: pros and consby scrottie (Scribe) |
on Jul 29, 2003 at 05:28 UTC ( [id://278729]=note: print w/replies, xml ) | Need Help?? |
Hi. Consider typesafety.pm rather than Class::Contract. Not only does it declare what is passed and returned, but it enforces argument types and expected return types to match the declaration (I forgot to check actual return types - whoops - next version). All I ever do is shameless self-plug here - I'm really sorry. Since I try to write useful things, I like to think that now and again something might actually be useful. Someone made a comment about trying to suss something out 5 delegation levels deep. OO code, ideally, shouldn't try to navigate more than one or two has-a layers away. Otherwise, code is unduely interdependent. The alternative is to proxy the requests. Each object should know how to get requests one step closer to the source, if indeed it has-a something that is useful that way. A little more work up front, but refactoring is much, much easier, and it is all about refactoring. Besides, if you use typesafety.pm and you change your interface slightly, it'll warn you what you broke. For a full writeup, see LawOfDemeter on perldesignpatterns.com. To actually address the question at hand, yes, delegate, by any means. Perl makes it easier to write good, clean OO - you can use run-time tricks to generate accessors that delegate, or modules like Class::Delegation. When writing Java, even if your IDE generates the stubs for you, you still have to look at all of that code. When faced with hundreds of thousands of lines of code, my mind swims, even if it is all perfectly neat and orderly. In fact, if no unique "landmarks" distinguish one part from another, I get lost. Inheritance, out of control, takes on the look and feel of a massive, non OO program. Every method is a local function in the current object. Objects just become larger and larger. This creates a sort of GodObject, PDP where no real structure between objects can be created because there is only one object, or a few objects hung directly off of it, and knowledge of the arrangement of those objects is centralized in the God Object. To really model things using OO, the LawOfDemeter must kick in, and objects should take on arrangements nimbley, without the oppression of a God Object. Put another way, you should be able to return different objects that represent different parts of the internal state of your application. From those objects, you should be able to query other objects. Each object should know its neighbors. It might take a few calls to go from point A to point C, but all of the points aren't lumped together in one place. I hope this helps. -scott
In Section
Meditations
|
|