What is the best way to return an error from a function when I'm already returning a value?

前端 未结 8 1895
盖世英雄少女心
盖世英雄少女心 2020-12-13 13:42

I wrote a function in C that converts a string to an integer and returns the integer. When I call the function I also want it to let me know if the string is not a valid num

8条回答
  •  春和景丽
    2020-12-13 14:06

    You can either return an instance of a class where a property would be the value interested in, another property would be a status flag of some sort. Or, pass in an instance of the result class..

    Pseudo code
      MyErrStatEnum = (myUndefined, myOK, myNegativeVal, myWhatever)
    
    ResultClass
      Value:Integer;
      ErrorStatus:MyErrStatEnum
    

    Example 1:

    result := yourMethod(inputString)
    
    if Result.ErrorStatus = myOK then 
       use Result.Value
    else
      do something with Result.ErrorStatus
    
    free result
    

    Example 2

    create result
    yourMethod(inputString, result)
    
    if Result.ErrorStatus = myOK then 
       use Result.Value
    else
      do something with Result.ErrorStatus
    
    free result
    

    The benefit of this approach is you can expand the info coming back at any time by adding additional properties to the Result class.

    To expand this concept further, it also applies to method calls with multiple input parameters. For example, instead of CallYourMethod(val1, val2, val3, bool1, bool2, string1) instead, have a class with properties matching val1,val2,val3,bool1,bool2,string1 and use that as a single input parameter. It cleans up the method calls and makes the code more easily modified in the future. I'm sure you've seen that method calls with more than a few parameters is much more difficult to use/debug. (7 is the absolute most I would say.)

提交回复
热议问题