Page 1 of 1

Class attributes set by constants or passed vars?

Posted: Wed Sep 20, 2006 10:30 am
by zeek
I am writing a class that is very specific to it's application, and will never be used outside this application. It is instantiated from within another class (which is instantiated from yet another class/parent). I have always tried to keep my classes self-contained, all attributes set at instantiation or through methods -- period.

Now this class needs the value of a constant that is declared in the application's config file. I am trying to learn the correct way to do things, so my question is:

Given the situation, would it be better to pass this value through two parent classes just so they can pass it to this third (child) class, or should this class simply refer to the constant (making it no longer self-contained)?

Posted: Wed Sep 20, 2006 10:44 am
by n00b Saibot
since you are after self-containment.. the variable can be passed through the parent classes (although I still think that defies self-containment.. somebody correct me if I am wrong).

I would also advise you to look into Registry pattern since you're into OOP

Posted: Wed Sep 20, 2006 10:44 am
by Mordred
If you're not gonna use it "outside" I can see no problem in calling your get-configuration-variable function in the class. Go on, we won't tell ;)

Thanks

Posted: Wed Sep 20, 2006 10:51 am
by zeek
n00b Saibot wrote: I would also advise you to look into Registry pattern since you're into OOP
Thank you, this is the information that I was looking for. It seems every time I ask a question, I learn that the answer is irrelevant, because there's a better way to approach the situation all together. Thank again.

Posted: Wed Sep 20, 2006 10:54 am
by Maugrim_The_Reaper
Using the constant directly in the class creates coupling. Moving the class elsewhere, or changing the config file syntax for example, will require you to edit the class to compensate for the change. The solution which maintains decoupling (or self-containment) is to pass the value though the constructor or via a setter method.

If your class suffers from parameter crowding (too many variables getting passed into the constructor), a value object or registry might be worth looking into. One simple method is to create a Config or Settings object which is responsible for reading a config file and storing its values. This Config object can then be "registered" to a Registry. Pass the Registry into the class, and take it from there. There's a few Config/Settings classes for reference. I use one (http://svn.sourceforge.net/viewvc/quant ... /Settings/) and of course the Zend Framework has one bundled as Zend_Config.

Might seem overkill, but the config classes are reuseable for most projects in the future...