Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. General talk
  3. The Lounge
  4. Recurring C++ and Qt anti-patterns
Forum Updated to NodeBB v4.3 + New Features

Recurring C++ and Qt anti-patterns

Scheduled Pinned Locked Moved The Lounge
126 Posts 17 Posters 70.9k Views 10 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • JonBJ JonB

    @kshegunov
    I like this: your claim/view is that Python is so slow in the first place that it can't get much worse with exceptions :)

    kshegunovK Offline
    kshegunovK Offline
    kshegunov
    Moderators
    wrote on last edited by kshegunov
    #90

    @JonB said in Recurring C++ and Qt anti-patterns:

    I like this: your claim/view is that Python is so slow in the first place that it can't get much worse with exceptions :)

    No, not exactly. I claim that you should compare things that are comparable to begin with. Python runs in a VM, while C++ runs on metal. It is context that defines the term, and "costly" in C++ terms isn't applicable, or justifiable in python. Think of it like this, fopen calls into the kernel, do you consider this costly? It can be, if you do it all the time, like opening a file reading a couple of bytes and closing it. But the point is, is this costly? "Well, it depends" is the correct answer. Or, as I mentioned already, is longjmp costly?

    What I'm trying to convey is that in python you don't even consider this stuff, because the almighty VM shields you from it, and you can say your exceptions are cheap, which I don't know, they might very well be. But you still pay for the VM, exceptions or no exceptions. On the other hand I can choose to use exceptions where they make sense and pay the handling code price, or I may choose not to in some places and declare things with noexcept, or I can do what Qt does and disable them altogether.

    But even when you're talking only C++ it's not absolute. As I stated, and I do stand by it, throwing isn't that much different than unwinding stack frame by stack frame, until you meet the handler. And in C/C++ the stack is king, it's god and spirit and the holy mother, and all that; and it's very fast, and it is hardware supported for a reason. I would hardly believe anyone claiming push and pop are coincidences, a technical curiosity if you will. So yeah, unwinding the stack "is as inevitable as the demise of capitalism", but it's done all the time for all reasons, some of which were mentioned, and it is by far a bad reasoning, rotten logic if I may, to say it makes throwing "costly".

    PS.
    That's one of my better missives, if I may be so bold to say so myself. ;P

    Read and abide by the Qt Code of Conduct

    1 Reply Last reply
    3
    • JonBJ JonB

      @kshegunov said in Recurring C++ and Qt anti-patterns:

      Eh, fine, amaze me.

      Well, of course now that you want them I can't find as many clear statements as I have come across in the past :) But we could start with this accepted answer on SO:

      In the Python world, using exceptions for flow control is common and normal.

      The Python cultural norm is somewhat different. In many cases, you must use exceptions for control-flow. Also, the use of exceptions in Python does not slow the surrounding code and calling code as it does in some compiled languages

      In other words, your understanding that "exceptions are for the exceptional" is a rule that makes sense in some other languages, but not for Python.

      Or https://stackoverflow.com/a/3743528/489865

      If you are using the exception as part of the standard control flow - which is the Pythonic "ask forgiveness, not permission" way

      For the "efficiency" question, although this may not be the post I had in mind I find in https://softwareengineering.stackexchange.com/a/351121

      The general consensus “don't use exceptions!” mostly comes from other languages and even there is sometimes outdated.
      In C++, throwing an exception is very costly due to “stack unwinding”.
      So in those languages exceptions are “too expensive” to be used as control flow. In Python this is less of an issue and exceptions are a lot cheaper.

      In Python, if I want to know if a key is in a dictionary the "Pythonic" way is

      try:
          abc = dict["key"]
      except:
          ...
      

      utilizing dict exception throwing on non-existent key rather than testing for existence....

      Want to test for a divisor being 0? Don't test it, divide and catch the exception.

      Am I good Python citizen? Am I, heck no! If nothing else, it gets in the way of having the choice to break on any exception in a debugger.

      jsulmJ Offline
      jsulmJ Offline
      jsulm
      Lifetime Qt Champion
      wrote on last edited by
      #91

      @JonB said in Recurring C++ and Qt anti-patterns:

      try:
      abc = dict["key"]
      except:

      Isn't pythonic way

      if "key" in dict:
         ...
      

      ?!

      https://forum.qt.io/topic/113070/qt-code-of-conduct

      JonBJ 1 Reply Last reply
      0
      • jsulmJ jsulm

        @JonB said in Recurring C++ and Qt anti-patterns:

        try:
        abc = dict["key"]
        except:

        Isn't pythonic way

        if "key" in dict:
           ...
        

        ?!

        JonBJ Online
        JonBJ Online
        JonB
        wrote on last edited by
        #92

        @jsulm
        No, the whole point is that the "Pythonic" way is precisely to go try ... except instead of checking via in, that's my point! Same with division by 0, and other cases. This is Python's "Ask for forgiveness, not for permission" philosophy. Note that personally I wrote

        Am I good Python citizen? Am I, heck no! If nothing else, it gets in the way of having the choice to break on any exception in a debugger.

        :)

        kshegunovK 1 Reply Last reply
        0
        • JonBJ JonB

          @jsulm
          No, the whole point is that the "Pythonic" way is precisely to go try ... except instead of checking via in, that's my point! Same with division by 0, and other cases. This is Python's "Ask for forgiveness, not for permission" philosophy. Note that personally I wrote

          Am I good Python citizen? Am I, heck no! If nothing else, it gets in the way of having the choice to break on any exception in a debugger.

          :)

          kshegunovK Offline
          kshegunovK Offline
          kshegunov
          Moderators
          wrote on last edited by kshegunov
          #93

          @JonB said in Recurring C++ and Qt anti-patterns:

          Same with division by 0, and other cases.

          Out of curiosity: How does python handle that, because as far as I know (I don't really know that much, but bear with me for a second) there's no (strong) typing and while dividing by int(0) is invalid, division by double(0) is valid?

          Read and abide by the Qt Code of Conduct

          JonBJ 1 Reply Last reply
          0
          • kshegunovK kshegunov

            @JonB said in Recurring C++ and Qt anti-patterns:

            Same with division by 0, and other cases.

            Out of curiosity: How does python handle that, because as far as I know (I don't really know that much, but bear with me for a second) there's no (strong) typing and while dividing by int(0) is invalid, division by double(0) is valid?

            JonBJ Online
            JonBJ Online
            JonB
            wrote on last edited by
            #94

            @kshegunov
            I am just reporting that the "Pythonic" way to do division, where the divisor might be zero, is to do the divide unconditionally and catch the exception. As soon as I see "Pythonic" I tend to ignore it, and do what I'd do in C++ instead, but that's just me :)

            What I can show you is the following output:

            >>> z = 1 / 0
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
            ZeroDivisionError: division by zero
            >>> z = 1.5 / 0.0
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
            ZeroDivisionError: float division by zero
            >>> 
            

            So you get a ZeroDivisionError either way (which you could catch in a try ... except ZeroDivisionError), though by the look of it the error message distinguishes between plain division by zero versus float division by zero :)

            kshegunovK 1 Reply Last reply
            1
            • JonBJ JonB

              @kshegunov
              I am just reporting that the "Pythonic" way to do division, where the divisor might be zero, is to do the divide unconditionally and catch the exception. As soon as I see "Pythonic" I tend to ignore it, and do what I'd do in C++ instead, but that's just me :)

              What I can show you is the following output:

              >>> z = 1 / 0
              Traceback (most recent call last):
                File "<stdin>", line 1, in <module>
              ZeroDivisionError: division by zero
              >>> z = 1.5 / 0.0
              Traceback (most recent call last):
                File "<stdin>", line 1, in <module>
              ZeroDivisionError: float division by zero
              >>> 
              

              So you get a ZeroDivisionError either way (which you could catch in a try ... except ZeroDivisionError), though by the look of it the error message distinguishes between plain division by zero versus float division by zero :)

              kshegunovK Offline
              kshegunovK Offline
              kshegunov
              Moderators
              wrote on last edited by
              #95

              @JonB said in Recurring C++ and Qt anti-patterns:

              As soon as I see "Pythonic" I tend to ignore it, and do what I'd do in C++ instead, but that's just me

              You're a wise man ... ;)

              What I can show you is the following output

              Thanks, curiosity satisfied. So python just raises an exception even if dividing by a double(0) is a valid operation. Fair enough.

              Read and abide by the Qt Code of Conduct

              JonBJ 1 Reply Last reply
              0
              • kshegunovK kshegunov

                @JonB said in Recurring C++ and Qt anti-patterns:

                As soon as I see "Pythonic" I tend to ignore it, and do what I'd do in C++ instead, but that's just me

                You're a wise man ... ;)

                What I can show you is the following output

                Thanks, curiosity satisfied. So python just raises an exception even if dividing by a double(0) is a valid operation. Fair enough.

                JonBJ Online
                JonBJ Online
                JonB
                wrote on last edited by JonB
                #96

                @kshegunov
                I don't want to get into a debate (I know what you're like :) ), and I do know about floating point numbers being approximate representations (though zero/0.0 does have an exact representation), but (IMHO!) it is only in your physics/quantum mechanics area that "dividing by a double(0) is a valid operation" (the area where you can magic-away infinities and so on!). In a program it is not. (What have I let myself in for...!)

                kshegunovK 1 Reply Last reply
                0
                • JonBJ JonB

                  @kshegunov
                  I don't want to get into a debate (I know what you're like :) ), and I do know about floating point numbers being approximate representations (though zero/0.0 does have an exact representation), but (IMHO!) it is only in your physics/quantum mechanics area that "dividing by a double(0) is a valid operation" (the area where you can magic-away infinities and so on!). In a program it is not. (What have I let myself in for...!)

                  kshegunovK Offline
                  kshegunovK Offline
                  kshegunov
                  Moderators
                  wrote on last edited by
                  #97

                  @JonB said in Recurring C++ and Qt anti-patterns:

                  I know what you're like

                  Hey! Words can hurt, you know! ;)

                  though zero/0.0 does have an exact representation

                  Yes, actually two representations, as with the actual zero. You have +0.0 and -0.0.

                  it is only in your physics/quantum mechanics area that "dividing by a double(0) is a valid operation"

                  Eh, I didn't write the IEEE standard. Take your beef with prof. Kahan.

                  In a program it is not

                  Actually if you look through the math.h implementations you're going to see a lot of handling for such cases. For example the people who wrote them had the decency to actually handle these special cases like log(0) returning -inf. While I agree it's not often useful to divide by zero it sometimes can be, so that's the reason to handle it like that, I assume.

                  Read and abide by the Qt Code of Conduct

                  JonBJ 1 Reply Last reply
                  5
                  • kshegunovK kshegunov

                    @JonB said in Recurring C++ and Qt anti-patterns:

                    I know what you're like

                    Hey! Words can hurt, you know! ;)

                    though zero/0.0 does have an exact representation

                    Yes, actually two representations, as with the actual zero. You have +0.0 and -0.0.

                    it is only in your physics/quantum mechanics area that "dividing by a double(0) is a valid operation"

                    Eh, I didn't write the IEEE standard. Take your beef with prof. Kahan.

                    In a program it is not

                    Actually if you look through the math.h implementations you're going to see a lot of handling for such cases. For example the people who wrote them had the decency to actually handle these special cases like log(0) returning -inf. While I agree it's not often useful to divide by zero it sometimes can be, so that's the reason to handle it like that, I assume.

                    JonBJ Online
                    JonBJ Online
                    JonB
                    wrote on last edited by JonB
                    #98

                    @kshegunov said in Recurring C++ and Qt anti-patterns:

                    You have +0.0 and -0.0

                    The next time someone asks how much money I have in my pocket I will remember to give this answer.

                    I have $123.45 to give away. I want to hand each person $0.00. How many people do I need to meet to get rid of all my cash? :)

                    kshegunovK 1 Reply Last reply
                    0
                    • JonBJ JonB

                      @kshegunov said in Recurring C++ and Qt anti-patterns:

                      You have +0.0 and -0.0

                      The next time someone asks how much money I have in my pocket I will remember to give this answer.

                      I have $123.45 to give away. I want to hand each person $0.00. How many people do I need to meet to get rid of all my cash? :)

                      kshegunovK Offline
                      kshegunovK Offline
                      kshegunov
                      Moderators
                      wrote on last edited by
                      #99

                      Here: https://en.wikipedia.org/wiki/Riemann_series_theorem
                      Knock yourself out ... ;P

                      Read and abide by the Qt Code of Conduct

                      1 Reply Last reply
                      1
                      • fcarneyF Offline
                        fcarneyF Offline
                        fcarney
                        wrote on last edited by
                        #100

                        Be careful with not doing things the pythonic way in python. A lot of the time doing it the pythonic way leverages the internals of the language. In other words it pushes the execution from the interpreter to the built in methods that are written in C. So it can have an effect on performance. I don't think the exception example does this though. There may be other reasons I am not aware of.

                        C++ is a perfectly valid school of magic.

                        1 Reply Last reply
                        1
                        • Kent-DorfmanK Offline
                          Kent-DorfmanK Offline
                          Kent-Dorfman
                          wrote on last edited by
                          #101

                          wait a cotton pickin minute! there is no explicit cast to double in python so the x/double(0) argument is invalid on that basis alone...and x/float(0) behaves as expected.

                          1 Reply Last reply
                          0
                          • fcarneyF Offline
                            fcarneyF Offline
                            fcarney
                            wrote on last edited by
                            #102

                            Uncomfortable admission:
                            I wrote windows specfic code today...

                            C++ is a perfectly valid school of magic.

                            sierdzioS 1 Reply Last reply
                            3
                            • fcarneyF fcarney

                              Uncomfortable admission:
                              I wrote windows specfic code today...

                              sierdzioS Offline
                              sierdzioS Offline
                              sierdzio
                              Moderators
                              wrote on last edited by
                              #103

                              @fcarney said in Recurring C++ and Qt anti-patterns:

                              Uncomfortable admission:
                              I wrote windows specfic code today...

                              We feel for you :D

                              (Z(:^

                              1 Reply Last reply
                              2
                              • fcarneyF Offline
                                fcarneyF Offline
                                fcarney
                                wrote on last edited by
                                #104

                                Here is a nice QML anti-pattern:

                                Column {
                                    Rectangle {
                                        height: parent.height
                                    }
                                }
                                

                                This one was "fun". Yeah, it doesn't necessarily detect the loop and it locks up the desktop (Gnome). So you have to kill the process manually from a terminal outside of the desktop (ctrl-alt-f4).

                                C++ is a perfectly valid school of magic.

                                ODБOïO 1 Reply Last reply
                                0
                                • fcarneyF fcarney

                                  Here is a nice QML anti-pattern:

                                  Column {
                                      Rectangle {
                                          height: parent.height
                                      }
                                  }
                                  

                                  This one was "fun". Yeah, it doesn't necessarily detect the loop and it locks up the desktop (Gnome). So you have to kill the process manually from a terminal outside of the desktop (ctrl-alt-f4).

                                  ODБOïO Offline
                                  ODБOïO Offline
                                  ODБOï
                                  wrote on last edited by
                                  #105

                                  @fcarney said in Recurring C++ and Qt anti-patterns:

                                  Gnome

                                  this code works properly on windows with Qt_5_14_0_MinGW_64_bit

                                  1 Reply Last reply
                                  0
                                  • JonBJ Online
                                    JonBJ Online
                                    JonB
                                    wrote on last edited by
                                    #106

                                    From https://forum.qt.io/topic/113223/check-whether-a-script-exists-by-script-name/14

                                    QProcess process;
                                    process.setStandardOutputFile(QProcess::nullDevice());
                                    if (!process.startDetached(progName, args))
                                    ...
                                    

                                    Would anyone care to comment on why C++ allows calling a static method off an instance without (seemingly) offering the option of a warning message for it? :) (C# doesn't let me write this.)

                                    kshegunovK 1 Reply Last reply
                                    0
                                    • SGaistS Offline
                                      SGaistS Offline
                                      SGaist
                                      Lifetime Qt Champion
                                      wrote on last edited by
                                      #107

                                      AFAIK, there's nothing wrong with that. It's just that in the case you are showing, the static method has a specific behaviour that makes it unsuitable to be called like that.

                                      Interested in AI ? www.idiap.ch
                                      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                                      1 Reply Last reply
                                      2
                                      • JonBJ JonB

                                        From https://forum.qt.io/topic/113223/check-whether-a-script-exists-by-script-name/14

                                        QProcess process;
                                        process.setStandardOutputFile(QProcess::nullDevice());
                                        if (!process.startDetached(progName, args))
                                        ...
                                        

                                        Would anyone care to comment on why C++ allows calling a static method off an instance without (seemingly) offering the option of a warning message for it? :) (C# doesn't let me write this.)

                                        kshegunovK Offline
                                        kshegunovK Offline
                                        kshegunov
                                        Moderators
                                        wrote on last edited by kshegunov
                                        #108

                                        @JonB said in Recurring C++ and Qt anti-patterns:

                                        Would anyone care to comment on why C++ allows calling a static method off an instance without (seemingly) offering the option of a warning message for it? :) (C# doesn't let me write this.)

                                        Because the class is known and that's all that matters. Whether you call it through an object or with its qualified name makes no difference. Actually, there's one widespread use of that in the Qt documentation:

                                        int main(int argc, char *argv[])
                                        {
                                            QApplication app(argc, argv);
                                            return app.exec(); // QCoreApplication::exec is static
                                        }
                                        

                                        Read and abide by the Qt Code of Conduct

                                        JonBJ 1 Reply Last reply
                                        2
                                        • kshegunovK kshegunov

                                          @JonB said in Recurring C++ and Qt anti-patterns:

                                          Would anyone care to comment on why C++ allows calling a static method off an instance without (seemingly) offering the option of a warning message for it? :) (C# doesn't let me write this.)

                                          Because the class is known and that's all that matters. Whether you call it through an object or with its qualified name makes no difference. Actually, there's one widespread use of that in the Qt documentation:

                                          int main(int argc, char *argv[])
                                          {
                                              QApplication app(argc, argv);
                                              return app.exec(); // QCoreApplication::exec is static
                                          }
                                          
                                          JonBJ Online
                                          JonBJ Online
                                          JonB
                                          wrote on last edited by JonB
                                          #109

                                          @kshegunov
                                          But that is not my point/question. Which is: this piece of code is not the first (or the last) where someone has mistakenly written this. If C++ wants it this way, would it not be a good idea by now for compilers to offer a warning option? There is reason that e.g. C# does not allow it.

                                          kshegunovK 1 Reply Last reply
                                          0

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved