Page 1 of 1
Instantianting a different object inside of a class?
Posted: Sat Mar 26, 2005 8:24 am
by neophyte
Is it good coding practice to instantiate a different object inside of a class? Would you do it by inclusion outside of the class and then instantiation within a method?
If not what is preferrred? Inheritance? Factory?
Thanks
Posted: Sat Mar 26, 2005 9:22 am
by feyd
inheritance would only be used when you are augmenting the original class. A factory, I find more useful when I need to build many of a particular object with varying set ups. If this object is being used in limited fashion, I don't see a problem in instancing it within a method, but if you are wanting to use a user specified object, then let the user pass that object in.
Posted: Sat Mar 26, 2005 9:56 am
by neophyte
In my case I have a class that creates an image gallery from a directory(s). But then I wanted a class that would dynamically create thumbnail images and save them in a directory if needed. The first class has a method that creates a table of thumbnails. It has a for loop. Within that for loop, I instantiate the other class, create the thumb nail, and then destroy the image identifier and then increment the loop. I'm wondering is this an effcient way to do it or is there a better way?
Posted: Sat Mar 26, 2005 10:13 am
by feyd
sounds logically fine to me.. but I'll defer to the master of OOP here, McGruff.

Posted: Sat Mar 26, 2005 10:14 am
by neophyte
Thanks Feyd.
Posted: Sat Mar 26, 2005 6:20 pm
by McGruff
I'm more of a learner than a master. It's BIG subject which takes a while to really master.
Your design sounds fine. The key with OOP design is to identify discrete roles and responsibilities and encapsulate these in different classes. Classes should be cohesive - see
http://c2.com/cgi/wiki?CouplingAndCohesion.
Small and tight is good. Creating one object to make a table and another specifically to make a thumbnail is exactly the kind of thing you should be doing. Re-use isn't all it's cranked up to be, but here you can easily use the same ThumbnailCreator elsewhere or swap it out for a different object if you need to.
This could easily evolve into what's called the Strategy pattern. In Strategy, a superclass defines some kind of processing but the child classes define the precise algorithm to be used. In this case that might be jpg's, gif's or png's - ie a ThumbnailCreator superclass could be extended by childs which create files in each format you need to use.
In saying that, I've never mucked about with GD stuff so I don't know if Strategy would be overkill. Maybe you could just pass a parameter to the ThumbnailCreator to tell it what to save as. Simplest is best - but if you do need different classes for different formats Strategy would be a good fit.