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

QDate doc: Null date in comparison



  • If I read the source code correctly, default constructed QDate instances are considered to be less than any valid ones and equal to each other. However this behaviour is not documented, so the question is: can I rely on it, or if it's better to explicitly address the null case?


  • Lifetime Qt Champion

    Hi
    You mean like
    QDate date;
    qDebug() << date << "is valid" << date.isValid();
    result:
    QDate(Invalid) is valid false



  • Hi @mrjj,
    I mean to get the latest date in a loop:

    QDate latest;
    for (auto obj : objList) {
        if (someCondition(obj) && obj.date() > latest) {
            latest = obj.date();
        }
    }
    

    Since (anyValidDate > QDate()) is true, the code above works. However the doc doesn't say what the result of comparison will be if either or both comparands are null, so should I write

    if (someCondition(obj) && (latest.isNull() || obj.date() > latest))
    

    or (if obj.date() can be null too and I really want a strict comparison)

    if (someCondition(obj) && ((latest.isNull() && obj.date().isValid) || (latest.isValid && obj.date().isValid && obj.date() > latest)))
    

    instead in case that the behavior changes in a later version?
    It seems that the documentation generally lack details like edge cases and often I need to read the source code.


  • Moderators

    @Sentret_C said in QDate doc: Null date in comparison:

    should I write

    if (someCondition(obj) && (latest.isNull() || obj.date() > latest))
    

    I think you should, IMHO.

    in case that the behavior changes in a later version?

    I don't think this is the most important reason.

    The most important reason is that the longer code is more explicit about your intentions. Someone who reads your code in the future will think, "Ah, so the author intended to compare against null dates this way", instead of "I wonder if the author thought about the possibility of the date being null...?"

    It seems that the documentation generally lack details like edge cases

    If it's not documented, a good rule of thumb is to treat it like undefined behaviour and don't rely on it. (The only decent exception I can think of is when you need to really squeeze every bit of optimization out of your code -- even then, proceed with caution)


Log in to reply