M
M
Mercury132022-04-01 11:11:19
OOP
Mercury13, 2022-04-01 11:11:19

How to come up with an additional table of virtual methods?

We have such a code. I greatly simplify, but still I'm talking about architecture, and not about compilability, right?

enum class ObjType { GROUP, LEAF };

class Obj {
public:
  virtual ObjType type() const = 0;
  virtual size_t nChildren() const = 0;
  virtual std::shared_ptr<Obj> child(size_t i) = 0;
  virtual QString tableData(int column, int role) = 0;
};

class Group : public Obj { … };
class Leaf : public Obj { … };


Why is this code bad? It's all about the tableData() function.
1. Obj doesn't need to know what the table looks like. And if, for example, the group says “17 leaves” instead of the name, then he should not know these things either.
2. Obj should not pull interface libraries such as interface framework (Qt) and internationalization. For example, we will someday make a console version of the same utility for automatically loading data.

Thus, the second table of virtual methods is brewing. The main one containing nChildren and child is always added to the code. Additional, containing tableData - only if we are dealing with a graphical interface.

You can, of course, write to QAbstractItemModel::data():
void MyModel::data(const QModelIndex& index, int role) {
  Obj* obj = toObj(index);
  switch (obj->type()) {
  case ObjType::GROUP: {
        // Куча всякой дряни с qobject_cast, switch(role), switch(index.column())
     }
  case ObjType::LEAF: {
        // Такая же дрянь
     }
  }
}

But it's cumbersome and ugly.

Here's how to do it "objectively"?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shamanov, 2022-04-01
@SilenceOfWinter

your Obj is a DTO object passing the data loaded by the OD from the database to the Widget/View for display

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question