THE PASZ.COM BLOG

Sunday, August 14, 2005

Acrtionscript: Working With Interfaces

I'm starting a new Flash project -- a strategy war game. Not only will this be the first project I'm going to build primarily with FAME, I've also decided to use interfaces extensively.

The typical description of interfaces usually mentions how great they are when you're working with a team of developers. But the question is, can interfaces help little old me working by myself? On the face of it, interfaces can seem like unnecessary overhead. I've definitely taken this position in the past. After all, they don't implement any functionality. But my hope is that they will impose some useful structure on my code, especially now that I'm working with MTASC's amazingly detailed compiler errors.

If you're using strict data typing (that is, putting the data type after each variable declaration, e.g. var myInt:Number), interfaces give you some added flexibility. For example, say I have several types of vehicles that have been derived from a Vehicle parent class. So I'll have a class Plane and Helicopter that extend Vehicle. Then I'll instantiate the objects myPlane and myHelicopter. Now I can define a function fly(flier:IFlier) that will take a vehicle object as a parameter, provided it implements the IFlier interface.
fly(myPlane);
fly(myHelicopter);
.
.
.


This method is better than being able to pass any subclass of Vehicle into fly() because the compiler will generate an error if a non-flier is passed in.
fly(myCar);
...
ERROR: type error Car should be IFlier


An alternative without interfaces would be to create multiple functions like this:
flyPlane(flier:Plane){...}
flyHelicopter(flier:Helicopter){...}
.
.
.

As you can see, this implementation is much messier.

One warning: If you have other objects that also implement IFlier you will be able to pass them into fly() as well. This may not be desirable!

If you're not strict about data typing in your code then I'm not sure interfaces can offer much for you. But if you have decided to enforce the discipline of strict typing on yourself, interfaces may complement your programming regimen, and can help you write code that is more consistent and organized.

3 Comments:

Post a Comment

<< Home