Pathologically Eclectic Rubbish Lister | |
PerlMonks |
Re: OO: Building an object of the right type based on a parameterby mstone (Deacon) |
on Mar 14, 2004 at 04:32 UTC ( [id://336454]=note: print w/replies, xml ) | Need Help?? |
Having a big case statement ("if client = A1 or A2 make a ::A, if client = C make a ::C, etc:) feels wrong. Good. That means you have the OO mindset. ;-) Whenever you find yourself thinking that you need a case statement that switches on an object's class, you should probably move the switched code into the objects themselves, as kappa suggested. Unfortunately, kappa's suggestion creates a circular dependency between the Client and InvoiceCalculator classes. That's not a disaster as design problems go (at least not in Perl... C++ is another story), but it's a good idea to get rid of circular dependencies whenever possible. In this case, you have two options:
Promoting creation to a higher class means doing something like so:
Every Client is associated with the right kind of InvoiceCalculator right from the start, so all we have to do is ask for it when we need it. Neither the Client nor the InvoiceCalculator actually creates the other, so the circular dependency is gone. We do still have two classes carrying references to each other, though, and that's a bit clunky. Demoting the shared information means creating a data storage class that both the Client and InvoiceCalculator classes can share:
This costs a few extra keystrokes to work with the embedded Storage object, especially if we decide to be really pure and use set() and get() methods to move data back and forth. Being pure does have its value, though, since the access methods give us a place to put sanity-and-hygiene code for the stored values. We can also use the more relaxed approach shown in InvoiceCalculator::calculate(), though, and twiddle the values directly. If we really resent the extra keystrokes, we can use a temporary reference:
In Section
Seekers of Perl Wisdom
|
|