Call function directly vs emiting Signal (Qt - Signals and Slots)

久未见 提交于 2019-12-03 20:36:17

Signals and slots are used to decouple classes so that they don't need to explicitly know who uses their functionality and how. In many cases, decoupling is a desirable trait of the design of your software. Of course it's not an end in itself, it's useful when it helps you to reason about the code's correctness and makes it easier to maintain. Decoupling help in understanding/reasoning about the code as it leads to smaller units of code that you can analyze in isolation. Another way to look at it is separation of concerns: let one unit of code do one thing, e.g. focus one class on one aspect of functionality.

When you have a pair of classes and wish to decide whether to couple them or not, think of whether they could be used with other classes. A could be coupled to B, but could the interface that couples the pair be used by C instead of B? If so, then some decoupling pattern must be used, and signal-slot pattern is one of them.

For example, let's compare how these two interfaces affect coupling with user code. The objective is simple: add debug output to an object's destructor:

class QObject {
  ...
  Q_SIGNAL void destroyed(QObject * obj = Q_NULLPTR);
};

class QObjectB {
  ...
  virtual void on_destroyed();
};

int main() {
  QObject a;
  struct ObjectB : QObjectB {
    void on_destroyed() override { qDebug() << "~QObjectB"; }
  } b;
  QObject::connect(&a, &QObject::on_destroyed, []{ qDebug() << "~QObject"; });
}

The signal-slot interface allows you to easily add functionality to existing objects without a need to subclass them. It is a particularly flexible implementation of the Observer pattern. This decouples your code from the code of the objects.

The second implementation, using the template method lookalike pattern, forces a closer coupling: to act on ObjectB's destruction, you must have an instance of a derived class where you implement the desired functionality.

Advantages of signal-slot mechanism:

  • easy to use when your class has no information about it's clients;
  • may be used for thread-safe calls;
  • you must not manually remember all objects to notify them;
  • the only rule to connect two objects is that they both must be QObject subclasses.

Disadvantages:

  • slower call (each signal emit scans list of all connected objects);
  • possibly complicated spaghetti-code; you don't know, who and when will call any slot or who will get emitted signal.

You should think yourself about your case. If there is no signal "listeners" outside the SetupViewManager, try direct calls. If someone else can connect to this signals, your choice is emitting them.

There also may be other reasons to use signals. But there is no reason to use them just to call a function. In one thread, at least.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!