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

Recurring C++ and Qt anti-patterns



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

    No, its just a bug in the code for a samich.

    Samich... Are you a yinzer?



  • @kent-dorfman said in Recurring C++ and Qt anti-patterns:

    Are you a yinzer?

    Had to look it up. Based on what I read, no. Not sure where I heard sandwich being called samich though. I am in western USA.


  • Moderators

    Being an a-hole as a recruiter:

    What does o() mean?
    What does o.o mean?
    What does o->o mean?
    What does o-->o mean?
    What does o()--<=>--o() mean? Fun fact - crashes MSVC (yes, the compiler, not the compiled program)
    What does [](){;o()++<=>++o();}() mean?


  • Qt Champions 2017

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

    I had to dig through this thing once, only the real code was like a hundred times longer and more convoluted.
    [Snip]
    Pretty ugly thing to debug, especially since once in blue moon it actually works :/

    Indeed. Although, this is windows specific. It works correctly on Linux as the symbol resolution happens at run time.


  • Moderators

    @chris-kawa wow, some of those you don't encounter every day...


  • Moderators

    Yeah, it was a bit out of topic. Here's one anti-pattern I encounter something like 9/10 code reviews:

    auto widget = new SomeWidget(some_widget);
    auto layout = new SomeLayout(some_other_widget);
    layout->addWidget(widget);
    

    It's not a correctness bug. It's a subtle performance one. Compare this with:

    auto widget = new SomeWidget();
    auto layout = new SomeLayout();
    layout->addWidget(widget);
    some_other_widget->setLayout(layout);
    

    If you don't see it - count how many times parents need to be changed and imagine there's not one but, say, 50 widgets and layouts.
    For extra sweetness do the same when the parent widget is visible - how many times layouts need to be recalculated?


  • Qt Champions 2019

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

    auto widget = new SomeWidget(widget);

    I hope this is a typo :-)


  • Moderators

    @jsulm Sure, sorry, fixed :)



  • @chris-kawa said in Recurring C++ and Qt anti-patterns:

    It's not a correctness bug. It's a subtle performance one. Compare this with:

    It took me a few minutes but ok, I'm convinced... LOL



  • mtime.toString(tr("M/d/yyyy hh:mm AP"));
    

  • Lifetime Qt Champion

    Hi @fcarney,

    mtime.toString(tr("M/d/yyyy hh:mm AP"));

    OMG. Yeah, that's a good (bad) one :)



  • Just created this pattern today:

    if(condition == somevalue)
    somestatement.append(whatever);
    

    I forgot the indentation so it didn't look like and if statement.
    I I know this is really simple and not an error/bad practice. It is more a readability issue.

    Going to be more rigorous in the future:

    if(condition == somevalue){
        somestatement.append(whatever);
    }
    

  • Lifetime Qt Champion

    Well, that one made a big security hole in Apple's authentication code but it was the other way around, several lines under the if without curly brackets.



  • Wow, okay, I take it back. Bad pattern!


  • Lifetime Qt Champion

    @SGaist I've seen GCC 7.3 warning about exactly this problem ("thif if clause ... does not guard ...").

    So hopefully such problems will go away sooner than later.

    Regards


  • Qt Champions 2017

    Nope. It warns if it doesn't actually guard (as if you had put incidentally ; at the end of the if):

    if (something)
    something else;
    something else else; //< Can't warn about that
    

  • Lifetime Qt Champion

    OMG

    QString CharToString(char *str)
    {
        QString result = "";
        int lengthOfString = strlen(str);
    
        QString s;
        for(int i = 0; i < lengthOfString; i++)
        {
            s = QString("%1").arg(str[i], 0, 16);
    
            if(s.length() == 1)
                result.append("0");
    
            result.append(s);
        }
    
        return result;
    }
    

    There are multiple anti-patterns in that function (who finds all?!), but basically the solution is to use: QString s = QByteArray::toHex(str);


  • Lifetime Qt Champion

    @kshegunov

    What I meant was the following example:

    8ac16113-6178-40b1-9ce0-232de08d5cb6-image.png

    which is already an improvement on poorly formatted code.

    Regards



  • Including the wrong header that doesn't match cpp file definition... This is really confusing.



  • Hmmm... I have just found some icky syntax that makes me think it is an anti-pattern just cause its icky:

    #include <vector>
    
    template <class T>
    class IteratorClass
    {
    public:
        std::vector<int>::iterator end(); // neat syntax
        std::vector<T>::iterator end2(); // error, needs typename
        typename std::vector<T>::iterator begin(); // really? this is getting ugly
        using retIterator = typename std::vector<T>::iterator; // ugly
        typedef typename std::vector<T>::iterator retIterator; // fugly
    
    private:
        std::vector<T> m_data;
    };
    

    Got stuck on this last night and just couldn't figure out why the simplest syntax would not work with templates. My IDE even told me I needed "typename" and I kept trying "typedef" (💩). Yeah, it was not a good time to be coding, so I went to bed. 😀



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

    std::vector<T>::iterator end2(); // error, needs typename

    Yeah, this being an error (inside a template definition) really bugs me as well.

    I'm sure there is a perfectly good brainiac reason it barfs, but I could really see myself wanting to do something like this, as "end2" instead of end2()



  • @Kent-Dorfman
    Apparently its a "dependent name":
    https://en.cppreference.com/w/cpp/language/dependent_name

    I have not taken time to understand it, but there is the "reason".



  • I think I may need to stop coding in the evening. I ran into a weird bug that I cannot duplicate today:

    #include <vector>
    
    template<class T>
    class SomeObject
    {
        using Storage = std::vector<T>;
    public:
        SomeObject(size_t len){
            m_data.resize(len);
        }
    
        size_t getSize(){
            return m_data.size();
        }
    
    private:
        Storage m_data;
    };
    
    class UsesSomeObject
    {
    public:
        UsesSomeObject()
            : m_someval(0)
            , m_somedata(128) // if not initialized the whole object was spitting out weird data
        {
    
        }
    
    private:
        int m_someval;
        SomeObject<int> m_somedata;
    };
    

    I don't know if this had anything to do with templates or not. I was working with one at the time. There is a comment in the above code about not initializing m_somedata. I didn't have a default constructor or maybe it created one for me (not sure). Accessing the vector internal to the class had all sorts of "interesting" behavior. Then when I realized my error everything started working fine. It was just a very sneaky issues. However, on my compiler at work it is not letting me compile this. So I am not sure of the situation where it would let me compile this. Maybe if it creates its own default constructor. The lesson is make sure everything is getting initialized before using them!

    I will check tonight to see if I can simplify the actual condition that caused this. It was quite interesting and the errors didn't match the source of the problem.



  • Not an antipattern, just disappointing. I cannot do this:

    std::vector<float&> frefs; 
    

    I know why. I know you can use std::reference_wrapper, but it is kinda messy to me.



  • I guess I don't have a problem with it because in the cases where I might ever consider such an abomination there are always pointers...yes, always pointers.



  • @Kent-Dorfman said in Recurring C++ and Qt anti-patterns:

    always pointers

    We should start an anti-safe coding movement (I say this with disdain for idea of safety, there is nothing safe about systems level coding IMO, or coding in general) . The slogan would be "Always Pointers".


  • Moderators

    I hate to break this to you guys but pointers and references are the same thing. References are just syntax constraint, something like const, so disappointment in this case would be like disappointment that you can't assign to a const value. IMO using std::reference_wrapper because you don't like those naked stars is just silly.
    As for "Always Pointers" - why so extreme? How about more mellow party like "pointers where they make sense"?



  • @Chris-Kawa said in Recurring C++ and Qt anti-patterns:

    pointers where they make sense

    That is the point (hehe) its an extremist group.



  • I tend to think of myself as a "moderate extremist": on the surface all agile, type-safe, and scope limiting...but in private I do stuff like macro-ize bitshift operations to save typing. My infatuation with pointers goes toward edumacating the noobs when they try to do large matrix processing using array indexes. It's like "hold my beer while I whack this kid"...and then I say "don't do that!"


  • Qt Champions 2017

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

    IMO using std::reference_wrapper because you don't like those naked stars is just silly.

    While I agree with you, it's rather funny (and somewhat ironic) such a class does exist.
    The chant "pointers are bad", and even the more extreme "naked pointers are even badder" seems to have crept so ubiquitously into the way code's written (even moved past a fad I'd say) that we need a wrapper object to make assignable something which was designed into the language not to be, instead of simply passing by address ... strange world we live in ...


  • Banned

    One example is using exceptions for control flow or as simply another way to return a value from a function.



  • @Bur8rus but...the C++ God himself himself wrote in the sacred texts that exceptions should be looked at as just another flow control route, and to not make any judgements other than that.

    While in principle I agree with you, I'm glad my hands are not tied to keep me from committing an abomination like generic flow using exceptions.



  • Heh, bad flow control discussions made me think of one phrase:
    goto hell ;-)


  • Moderators

    @fcarney said:

    goto hell ;-)

    I guess this calls for a classic:

    int up;
    throw up;
    


  • or

    If if THEN then
    

    There once was this home computer language called BASIC, done as a ROM interpretor, that was supported on meager 4KB RAM 8-bit machines. If you wanted to do something quickly then you stuffed your machine code into a preallocated string variable, and then you did a function call like rv=SYS(code$) to execute the machine code directly.



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

    One example is using exceptions for control flow or as simply another way to return a value from a function.

    Depressingly, for those of us forced to use Python (with Qt) we are encouraged to use exceptions for flow handling etc. Under the mantra that Python exceptions are different from/more lightweight than C++ exceptions....


  • Qt Champions 2017

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

    Depressingly, for those of us forced to use Python (with Qt) we are encouraged to use exceptions for flow handling etc. Under the mantra that Python exceptions are different from/more lightweight than C++ exceptions....

    They're not, obviously. However in all fairness exceptions have their place, just not in the way they're abused. I use them for quick escape through the stack in numerical code, where it'd be borderline stupid to sprinkle std::optional with if-ery everywhere to handle an error deep in the code. As everything, though, one should apply the very old and tested "common sense" ...



  • @Kent-Dorfman I still have C64 (my first computer bought in 1988) and I still use Basic for the fun of it :)



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

    They're not, obviously.

    I take it that is against my "Python exceptions are different from/more lightweight than C++ exceptions"(?) Well, apparently, this is true. I could (if required) give several references. I guess we cannot assume that a Python exception maps to a C++/OS/native exception....


  • Qt Champions 2017

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

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

    They're not, obviously.

    I take it that is against my "Python exceptions are different from/more lightweight than C++ exceptions"(?)

    Yes, that's correct. More so I was referring to the "lightweight"-ness, not so much about them being different. I could agree if you can show a VM's exception to be lighter than a hardware's stack unwinding, but that's rather dubious. Basically that'd be like saying that Python's exceptions are faster than a C longjmp, arguable at best.

    Well, apparently, this is true. I could (if required) give several references.

    Eh, fine, amaze me.

    I guess we cannot assume that a Python exception maps to a C++/OS/native exception....

    Nor had I done that. The underlying tech is different to jump to such a conclusion.


Log in to reply