PDA

View Full Version : Correct way to pass a reference?



sceneshift
March 25th, 2008, 04:53 AM
Hi,

Can someone please set me straight on how to communicate properly over different classes. Lets say I have two classes, one is "photo" and the other is "album"... in this instance, both classes are instantiated from my "main" class. Currently, in order to get "photo" to communicate (read variables, start methods) I've been setting them up in my main class like so:



public static var photoClass:photo = new photo();
public static var albumClass:album = new album();

And then inside of photo I would code:



main.albumClass.method();

This works fine, but I am told using static variables is a bad idea, and a better way to do it would be to pass each class as a reference, for example:



public static var photoClass:photo = new photo();
public static var albumClass:album = new album();

photoClass.init(albumClass);

Please help! I like using the first method, but if it's bad then I'd rather get out of the habit now!

Thanks

amarghosh
March 25th, 2008, 05:04 AM
first of all, try to make it a habit to use InitialCaps for class names:
so class names would be Main, Photo, Album etc;

Main class can be something like:


package
{
import flash.display.Sprite;
public class Main extends Sprite
{
public var photo:Photo;//assuming Photo and Album are in default package
public var album:Album;
public function Main()
{
this.photo = new Photo();//"this" is optional
this.album = new Album();
this.album.addPhoto(this.photo);
}
}
}

sceneshift
March 25th, 2008, 05:08 AM
Thanks for the reply.

Any reason why that method is better than using static variables?

amarghosh
March 25th, 2008, 05:15 AM
see it like this:
what if "text" property of TextField class was static? if u have 3 TextFields on stage all will contain same text only; u change one and all r changed? would u like it?

basically in OO programming, static variables are used when u wanna describe some characteristic that is common to all the instances of a class. say in a CustomTextField class that u define, u might wanna set default text color as red: then u can have
private static var defaultColor:uint = 0xff0000;
and in the constructor u can assign
this.textColor = defaultColor
//not the best example for static & instance variables though;