Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to refactor this if else code containing object constructors?



  • QWidget *MyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const
    {
    QLineEdit *lineEdit = new QLineEdit(parent);
    if (index.column() == 0)
    {
    QRegularExpression regExp(REG_EXP1);
    QRegularExpressionValidator *validator = new QRegularExpressionValidator(regExp, parent);
    lineEdit->setValidator(validator);
    }
    else
    {
    QRegularExpression regExp(REG_EXP2);
    QRegularExpressionValidator *validator = new QRegularExpressionValidator(regExp, parent);
    lineEdit->setValidator(validator);
    }
    return lineEdit;
    }

    There must be a way of refactoring this so that it is shorter.



  • Hi @Guerrian,

    There must be a way of refactoring this so that it is shorter.

    Well, shorter is not necessarily always best (eg when it reduces readability), but in this case, I'd write it like:

    QWidget *MyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const
    {
        QRegularExpression regExp((index.column() == 0) ? REG_EXP1 : REG_EXP2);
        QRegularExpressionValidator *validator = new QRegularExpressionValidator(regExp, parent);
        QLineEdit * const lineEdit = new QLineEdit(parent);
        lineEdit->setValidator(validator);
        return lineEdit;
    }
    

    or possibly:

    QWidget *MyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const
        QRegularExpression regExp((index.column() == 0) ? REG_EXP1 : REG_EXP2);
        QLineEdit *lineEdit = new QLineEdit(parent);
        lineEdit->setValidator(new QRegularExpressionValidator(regExp, parent));
        return lineEdit;
    }
    

    It is possible to make it even shorter, but I think readability begins to be impacted then.

    Cheers.


Log in to reply