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

What should be returned by a method that fails to construct the object it has to return ?..



  • Hello,
    i have a method that should read a JSON file, construct QList of Tool* and return it ,
    i wonder what should i return if the json file is not found. This must be a basic (silly ?) question sry

    QList<Tool*> ToolLoader::loadTools(QString name){
      QFile jsonFile(name);
      if(jsonFile.open(QFile::ReadOnly)){
        // construct a list of Tools and return it
      }else{
        // what to return if file can not be opened ?
      }
    }
    

    Thank you


  • Qt Champions 2019

    It can throw, it can take a second parameter bool *bOk, it can return an empty list, ... it depends on what you want and define.


  • Qt Champions 2019

    It can throw, it can take a second parameter bool *bOk, it can return an empty list, ... it depends on what you want and define.



  • hi @Christian-Ehrlicher thank you for replying
    currently i am returning an empty list, then the caller of the method has to check the list, but i tought it was bad to return anything at all in this case.
    I would like to not return anything
    I will read about exceptions.
    Thank you.



  • @LeLev If you have a return type that is an object you have to return that object. If its a pointer you can return nullptr. If its a list you have to return a list (empty if its empty).



  • In such cases, I have started using std::optional or a custom sum type which can either return a value or error information, basically a nice wrapper around

    template<class T>
    std::variant<T,MyErrorClass>
    

    The latter has the advantage that you can provide information why no value was returned, and (if you consistently use this pattern) you can pass the "value-or-error" sum type through multiple levels of calls without having to put an "if" statement checking for errors after each call.



  • I always throw on a failed constructor so that the object pointer is left alone and nothing becomes "partially initialized". Being that you are wrapping the object construction in an additional layer, you could throw to your method and record status as a return code. I prefer the following standard for method prototypes where possible.

    status = method(outparam&, inparam, inparam=value);


Log in to reply