Handling interface segregation in C++

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.

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

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Handling interface segregation in C++

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.

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

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật