I have faced difficulties trying to return a result combined with the set of errors from function call.
I have started from the following approach
List<String> errors;
bool result = Obj.GetResult(out errors, int id);
The second step was to introduce new class
public class OperationResult
{
public bool Result {get;set;}
public List<string> Errors {get;set;}
}
But then the dirty code started to appear inside the GetResult method.
For example
public OperationResult GetResult(int id)
{
if (id == 0)
{
return new OperationResult { Result = false, Errors = {"Error"}};
}
if (id < 400)
{
var result = new OperationResult { Result = false, Errors = {"Error"}};
if (id >200)
result.Errors.Add("Error");
return result;
}
}
Then I’ve started to worry not allowing result user to edit the result they get.
I have extracted interface from the OpearationResult class which was able only to read data.
Now I’m want to add result builder class…
And at this point I’ve started to thinking that I’m doing something wrong. Trying to reinvent the bicycle, or just creating problems out of the air.
Please give me an advice, how to handle all this stuff.
I am also curious how this is handled in the functional programming languages. (I mean immutability)
This might be a time to start throwing exceptions.
In his book Clean Code, Robert Martin talks about the confusion and lack of readable code when you do something like:
Because it would appear from reading the code that CanLogOn should simply return a bool indicating if the user is allowed to log on, but now it’s getting a custom result object that has error codes etc. This will cause you to further pollute your code with things like
instead of
or even better
and let it decide if it can or not.
This is a simplified example, because I’d assume apart from a DB exception there isn’t a lot of possible errors that can occur in a CanLogOn() method.
While you shouldn’t use exceptions for normal flow, they are there, in part, to prevent this pattern of output values, and error codes on the return, and needing to know the difference between a return code of 200 and 402 and -134.
It will make your code cleaner, easier to read, and might prompt you to examine if you really need all those exceptions, and if so, is this method the best place to throw them from.