PDA

View Full Version : Best Practice for code location


bob56
03-23-2012, 01:43 PM
Hi All,

I would like to better understand how to structure my code and need some help in understanding Best Practices. My example is below:

Say i have 4 classes, Class A, Class B, Class C and Class D. Each class uses the following class in turn so Class A will use Class B, Class B will use Class C and Class C will use Class D.

Eventually i will need 3 instances of Class A. My question is should i instantiate Class B inside Class A, Class C in Class B and so on? Or should i be instantiating all these classes in one main location, Main.as? I suspect the latter is the case, if so is this always the general rule of thumb, for visibility?

If the latter is the case then should i ideally pass Class A object to Class B via Class B's constructor? Or can it equally be passed via a function in Class B?

I just want to know that once all the classes are created and you start using the classes should they all be instantiated and worked with in one general location or are there situations (maybe like above) where this rule may not be followed.

Thanks.

wvxvw
03-23-2012, 09:35 PM
The question may be a bit too abstract, but I'll try to answer it in a same a bit too abstract way: it is usually better to create or declare things as close as possible to the place they are used.

On a more general scale, there is such thing as Demeter's laws (nothing is a law, it's just a general direction, an advise, you should understand and act accordingly). These laws are intended for keeping the code modular. You may read up on it here: http://en.wikipedia.org/wiki/Law_of_Demeter )

peptobismol
03-23-2012, 10:46 PM
It depends what you're trying to do. I don't think I can answer your question.

Imagine if a stranger had to go into your code to add to and modify, how easy would it be. If it's unorganized to hard to find things, then it's probably is.

bob56
03-24-2012, 10:03 AM
Thanks guys, the article is great, it's given me a better understanding of what i should be aiming to achieve when writing code.