Megidd
Megidd

Reputation: 7952

Deciding between signal-slot mechanism versus traditional loop

I want to update many objects. I have the option to do so with traditional loop like:


void ParentClass::updateItems(const float factor)
{
     for (Item *item : items()) {
        item->update(factor)
    }
}

... or I can do it with signal-slot mechanism like:

class ParentClass : public QObject
{
    Q_OBJECT

Q_SIGNALS:
    // The signal which will be emitted by parent:
    void updateNeeded(const float factor);

private:
    void updateItems(const float factor);
}

// Signal is emitted here
void ParentClass::updateItems(const float factor)
{
     emit updateNeeded(factor);
}


class Item : public QObject
{
    Q_OBJECT

    Item(ParentClass *parent) : QObject()
    , m_parent(parent)
    {
        // Connect parent signal to each item slot at each item constructor
        QObject::connect(m_parent, &ParentClass::UpdateNeeded, 
                         this, &Item::handleUpdate);
    }

public Q_SLOTS:
    void handleUpdate(const float factor);

private:
    ParentClass *m_parent;
}


// The slot which handles emitted signal:
void Item::handleUpdate(const float factor)
{
    this->update(factor);
}

  1. I have tested the loop approach and it works.
  2. I'm thinking on signal-slot mechanism, maybe it has some benefits for complex code.
  3. I wonder which approach is how it should be done or is there a better way?

After writing my question, I found this post which is really helpful but I"m not sure if it is directly related to my question.

Upvotes: 4

Views: 205

Answers (1)

darune
darune

Reputation: 10972

Use the loop based approach whenever and whereever you can, KISS

signal-slot is a very loose-coupled method of interfacing - while this can be great sometimes (mostly when other options are not possible..) it is much more brittle than regular function calls.

Upvotes: 2

Related Questions