mercredi 13 décembre 2017

How to avoid too many type casting and nullptr checking with c++

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
}

auto label = static_cast<Label*>(getUiWidget(buttonName));
if (label != nullptr) {
  // something happens
}

I personally don't like this as there are little 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 &NullLabel;
     else 
        return new Label(_labelName)
   }
   Button* getButton(string _buttonName) {
     if (//buttonName is in widget layout) 
        return &NullButton;
     else 
        return new Button(_buttonName)
   }
   ...
}

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 this really the best approach? Or is there a better solution?

Aucun commentaire:

Enregistrer un commentaire