views:

231

answers:

2

The argument to my method func() must implement the two unrelated interfaces IFoo and IBar. Is there a better way of doing this than declaring another interface only for this purpose that inherits from IFoo and IBar and using that interface as the argument type?

public interface IFooBar extends IFoo, IBar {
}

public function func(arg:IFooBar):void {
}

I'm developing for Flash Player 9.

Specifics of what I'm trying to do:

I'm writing a small library of classes that are intended to help me in the developing Flash games. To help in debugging and verification of game results the library requires that the user splits the game into the following components:

  • rawInputProducer: Produces device input events from either flash input events, saved events from a previous session, or some other source
  • rawInputProcessor: Listens to device input and from them produces user commands
  • gameController: Listens to user commands and updates the game state
  • gameView: Listens to game state changes from gameController and updates the stage

All these components generate events (called 'messages' to not confuse them with flash events). The class Engine initiates the components and runs the main loop.

In order to allow for components to be as generic as possible Engine only requires that they implement IMessageDispatcher and ITickable. I will want to write classes that are only a IMessageDispatcher or only ITickable. I also have a generic MessageDispatcher that implements IMessageDispatcher that my components probably will extend.

The original question regards how I can declare a method like the following:

Engine.setGameController(controller: ITickable & IMessageDispatcher):void
+1  A: 

Declaring an interface that extends both (or all) of the required interfaces is the correct way to do it. I can't think of a better way.

Amarghosh
you mean "extends", not "implements"
maxmc
@maxmc ya, fixed. I guess I _implemented_ OP's error :)
Amarghosh
+1  A: 

Having an interface extend 2 unrelated interfaces just so you can "correctly" type the parameter of one function / method seems like a code smell. You can get away with it, but I think it might be a symptom a design problem.

I might be wrong, though, as I don't know anything about your particular problem. And I'm assuming both IFoo and IBar are unrelated, which might not be the case.

Perhaps if you describe a bit more your problem, what these interfaces represent and how the method in question deals with the object that implements both interfaces, other people could suggest alternatives to your design (if that happens to be necessary). But, as a general rule of thumb, if you're doing it just to keep the compiler happy, there's a chance you're doing something wrong.

Juan Pablo Califano
+1 i agree with the code smell...
OXMO456
Added specifics of what I'm trying to do as you suggested
Anders