So a large legacy code base has structure that looks something like this.
We have a base app that has this public interface:
// Base app
class BaseApp {
public:
...
Widget* getUiWidget(string _widgetName);
...
}
However, our widgets are implemented like this
// Widget structure
class Widget {
...
}
class Button : public Widget {
...
}
class Label : public Widget {
...
}
The problem is everywhere in our view code we have a bunch of calls that look like this:
auto button = static_cast<Button*>(getUiWidget(buttonName));
if (button != nullptr) {
// something happens
button->doSomething1();
}
auto label = static_cast<Label*>(getUiWidget(buttonName));
if (label != nullptr) {
// something happens
label->doSomething2();
}
I personally don't like this as there are literally thousands of calls like this and I feel it could be done much better.
My intuition tells me I can do something like this
// Base app
class BaseApp {
public:
...
Widget* getUiWidget(string _widgetName);
Label* getLabel(string _labelName) {
if (//labelName is in widget layout)
return new NullLabel;
else
return new Label(_labelName)
}
Button* getButton(string _buttonName) {
if (//buttonName is in widget layout)
return new NullButton;
else
return new Button(_buttonName)
}
...
}
Where the null objects are
class NullButton : public Button {
public:
// override all methods of button and do nothing with it
}
class NullLabel : public Label {
public:
// override all methods of Label and do nothing with it
}
So the code :
auto button = static_cast<Button*>(getUiWidget(buttonName));
if (button != nullptr) {
// something happens
button->doSomething();
}
// Would turn in to
auto button = getButton(buttonName);
button->doSomething1();
My issue with this approach is that we have n number of widget children like toggle, slider, etc. So, in order to implement this, I would need n number of getSomeWidgetChild
and also I would need to write n number of NullSomeWidgetChild
.
Is there a better solution?