8

I'm designing a "view" handling system for a game. The goal is to be able to have different "views" that can be shown in sequence or stacked on-top of each other. For example, the initial splash screen is one View and the main menu that follows the splash screen is also a View which is rendered when the splash screen terminates. The camera view of the game world is also a View and the HUD is a View that is rendered on top of the game View.

While defining the interface for View I realize that the stacked nature of Views corresponds to the input focus priority. I.e. the View that's at the top of the stack should be offered to act on any user input before any other Views because in essence it is in the "foreground" for focus.

So the design of the interface for View looks like this at the moment:

/**
 * Interface for a "view". A view is a renderable target that can accept user input.
 *
 * One can think of it as a "layer", many layers can be drawn over each other in a
 * stack like fashion where the input focus travels from the top to the bottom of
 * the stack.
 */
class IView{
public:
    virtual ~IView() {}

    IView(const IView&) = delete; // Not allowed
    void operator = (const IView&) = delete; // Not allowed

    /**
     * Called to handle user keyboard input. May be called multiple times per update.
     * @param aKeyEvent The type of input event.
     * @param aKeyCode The key code of the event key.
     * @param aKeyboardState The current state of they keyboard.
     * @return True if the event was handled. False if the event should continue to lower views.
     */
    virtual bool handleInput(KeyEvent aKeyEvent, KeyCode aKeyCode, const KeyboardState& aKeyboardState) = 0;

    /**
     * Called to handle user mouse clicks. May be called multiple times per update.
     * @param aMouseButtonEvent The event to handle.
     * @param aMouseButton Which button it was.
     * @param aMouseState The current mouse state.
     * @return True if the event was handled. False if the event should continue to lower views.
     */
    virtual bool handleInput(MouseButtonEvent aMouseButtonEvent, MouseButton aMouseButton,
                             const MouseState& aMouseState) = 0;

    /**
     * Called to handle user mouse movement. Only called once per update.
     * @param aMouseEvent The event to handle.
     * @param aMouseState
     * @return True if the event was handled. False if the event should continue to lower views.
     */
    virtual bool handleInput(MouseMoveEvent aMouseMoveEvent, const MouseState& aMouseState) = 0;

    /**
     * Called when this view becomes the foreground view.
     */
    virtual void foreground() = 0;

    /**
     * Called when this view loses its foreground status and
     * has another view drawn over it.
     */
    virtual void background() = 0;

    /**
     * Called once every frame to perform periodic processing and rendering.
     */
    virtual void update() = 0;
};

This isn't the final interface, I'm just prototyping at the moment. But it gives you an idea.

Consider a game View, with a HUD on top, and then the game is paused so a pause View is rendered on top of the HUD. The pause View is offered first chance to act on user input to continue the game and it swallows all other input. To me this makes perfect sense.

Now, not all Views are necessarily interested in receiving input. Some might only be interested in mouse events and some might only be interested in keyboard events. My initial approach was to just let them have pass-through input handlers. But then I remembered the Interface Segregation Principle so it would make sense to define two more interfaces IKeyboardHandler and IMouseHandler and let the relevant View classes implement those when needed. But then I need to use dynamic_cast when passing input to the View objects to see if a particular View implements for example IKeyboardHandler.

I'm not sure if this approach is any more elegant than having empty input handlers and I'm looking for input and ideas on the design.

2 Answers 2

6

The interface segregation principle is focused more on completely irrelevant functionality. Here it's not so clear cut.

A blatant example of a violation of ISP is a Scrollbar interface with a setText function inherited from Widget, when a scrollbar won't even show any text. In such a case, the function may even be documented as irrelevant to callers, and to attempt to call such a function on a scrollbar may indicate a logical error.

Such blatant violations of ISP tend to be most foul, with monolithic interfaces that might have 200 functions with only 20 of them being relevant for the actual object in question. I see it often in GUI designs which are based around massive inheritance hierarchies, and often with documentation mechanisms trying to filter out the enormous amount of irrelevant derived functionality.

In your case, I think it's a bit different since given a function like this:

virtual bool handleInput(KeyEvent aKeyEvent, ...) = 0;

... it's still relevant to clients whether or not a view handles keyboard input. The fact that it doesn't is still relevant information, and worth calling the function to find out. So I don't see this as a clear violation of ISP.

You could try to split up the interface into multiple interfaces like IKeyboardHandler, but it's likely to make things harder rather than easier. It's worth noting the scope here in terms of dependencies.

A game will typically only have a handful of such views. You might have a main menu screen of sorts, splash screen, HUD, game view, maybe an in-game pie menu or something. It's a handful of views. The clients will also tend to be few in number, maybe just one broad client which is the one handling events from the operating system and calling the relevant view functions. So it's very limited in scope/scale when it comes to the number of dependencies, and that's a sign that you don't need to try too hard to come up with a great engineering solution, and that doing so may very well contradict your goals for ease of maintenance (ease of change).

Avoiding the Dynamic Cast

That said, just for completeness, I'll show you a simple way to avoid the cast in these kinds of scenarios. You can do this:

class IView{
public:
    ...

    // Returns null if keyboard handling is unsupported.
    virtual IKeyboardHandler* keyboard() = 0;

    // Returns null if mouse handling is unsupported.
    virtual IMouseHandler* mouse() = 0;
};

... view types that don't need inherit from (implement) IKeyboardHandler can simply return null, e.g. Ones that do can simply return this;. This way you can find out if a view supports keyboard handling with an interface query which doesn't involve casting, and if so, handle keyboard input for that view.

Taking this technique further to a greater degree of flexibility will often have you approaching COM-style designs (which does involve casting but hides it from the client), and even further, entity-component systems (which can be very useful to know about as a game developer, but probably outside of this view context). Yet I think this is absolute overkill for your case even with the basic form, and likely to just add more burdens upfront without alleviating any later.

Yet this basic version shown above can be a useful design technique if you had, say, functions in your system which can work strictly with IKeyboardHandler, and you potentially have things other than views which might implement this keyboard handling interface.

1
  • 1
    Good answer. I would however recommending using a Null Object rather than returning null from the event handler getters, as this would simplify client code. This could be returned by the base class methods to simplify implementation of View subclasses.
    – Jules
    Commented Jan 8, 2016 at 6:33
1

Don't use a pattern just because someone says it's a good idea. Following design patterns is an antipattern.

It looks to me like keyboard and mouse handling absolutely should be part of View, not something else.

There should probably be a ChainedView base class that implements View, which offer a default implementation of the virtual methods for keyboard and mouse handling. Some Views, like pause, will override that to only accept input they understand and ignore the rest - or maybe they won't even be a ChainedView. Most Views will override it to handle what they can and pass the rest onto the next chained view. Any View that doesn't need to handle input itself will automatically pass it on, so there is already separation there.

4
  • What do you mean with following design patterns is an antipattern?
    – Emily L.
    Commented Oct 5, 2014 at 15:25
  • 1
    @EmilyL. The entire concept of "design patterns" exists entirely to sell books about design patterns. In real code, the important question is "what will make this code maintainable?" Sometimes you'll make a decision that can be classified as a design pattern, but there is never a checklist.
    – o11c
    Commented Oct 5, 2014 at 16:53
  • @EmilyL o11c is correct in his first sentence, wrong in the second sentence. Don't just use them blindly. But definitely do follow them. Design patterns are time tested patterns found in huge swaths of successful code. For the specific case of the Gang of Four book, there's a large amount of evidence to support the value of each pattern. The patterns give you, the developer, guidance when designing software -- they are your starting point for any design because the patterns lead to good practices. But you do have to understand why each pattern leads to good code or else you get code bloat.
    – SRM
    Commented Jul 7, 2015 at 19:54
  • @SRM Thanks. I'm aware of that, and disregarded the second sentence. :)
    – Emily L.
    Commented Jul 7, 2015 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.