I am working on a slide-based application in C++.
Each slide has a slide-items collection which can
include items like caption, button, rectangle, etc.
Only some of these items support fill, while others
don’t.
What is the best way to implement the fill for the slide items in this case?
Here are two ways that I thought of:
-
Create an interface
Fillableand implement this interface for slide items
which support fill, keeping all the properties related to fill in the interface. When iterating over the list of slide items, dynamic_cast them
intoFillable, and if successful, do the operation related to fill. -
Make a
fillclass. Make afillpointer a part of slide item class, assign the
fillobject to thefillpointer for those objects which support fill, and for rest of them keep it null. Give a functionGetFill, which will return thefillfor the items if it exists otherwise returnsNULL.
What’s the best approach for this? I’m interested in performance and maintainability.
I would do a combination of the two. Make your
Fillableinterface and have it be the return type for yourGetFillmethod. This is better than the dynamic cast approach. Using dynamic cast to query for the interface requires that the actual slide item object implement the interface if it is to support it. With an accessor method likeGetFillhowever, you have the option of providing a reference/pointer to some other object that implements the interface. You can also just returnthisif the interface is in fact implemented by this object. This flexibility can help avoid class bloat and promote the creation of re-usable component objects that can be shared by multiple classes.Edit:
This approach also works nicely with the null object pattern. Instead of returning a null pointer for the objects that don’t support
Fillable, you can return a simple no-op object that implements the interface. Then you don’t have to worry about always checking for null pointers in the client code.