Wednesday, August 26, 2009

don't pass variables through classes

Sometimes I find myself writing dangerous code like this:


public class UFO
{
public function UFO( alienColor : uint )
{
var alien = new Alien( alienColor );

...
}
}


It's dangerous because I'm passing UFO a parameter that it doesn't use. All it does with that parameter is pass it through to Alien's constructor.

Why is this dangerous? Well, first of all, it makes the code difficult to understand. You're probably not confused my example, above, because I made it purposefully simple. In real-life examples, when I give myself license to pass-through parameters, I tend to pass them through multiple levels:


public class UFO
{
public function UFO( alienColor : uint )
{
var bridge : Bridge = new Bridge( alienColor );

...
}
}

public class Bridge
{
public function Bridge( alienColor : uint )
{
var alien = new Alien( alienColor );

...
}
}


This is also dangerous because it's ugly. You should pass a constructor only the info necessary to construct its class. The construction crew building the UFO and its bridge don't need to know the alien's color.

Finally, it's ugly because it makes testing difficult. alienColor has multiple chances to get messed up (e.g. set to some illegal value) before it reaches its intended target, Alien.

So how should I write this code? Well, UFO doesn't need to know anything about an alien's color. It just needs a completed alien so that it has a pilot (to help it destroy the Earth!). So I should first construct an alien and then pass it to UFO.


var alienColor : uint = 0xFF00FF;
var alien : Alien = new Alien( alienColor );
var ufo : UFO = new UFO( alien );


or, if there's a bridge in the UFO, I should code like this:


var alienColor : uint = 0xFF0000;
var alien : Alien = new Alien( alienColor );
var bridge : Bridge = new Bridge( alien );
var ufo : UFO = new UFO( bridge );

No comments:

Post a Comment