tags:

views:

35

answers:

1

I'd like to know if there is any consensus on what is better practice in this general statement type.

if(CouldDoSomething())
     DoThatThing();
else
     WriteErrors(GetTheErrorsThatWouldHaveResulted());

This may require twice as much work .as you have to check for potential problems, then either do the thing you wanted to do or go back and get error messages.
It also requires 3 separate functions:
CouldDoSomething DoThatThing and GetTheErrorsThatWouldHaveResulted

whereas

string errorString=TryToDoSomeThing();
if(!string.isNullOrEmpty(errorString))
     WriteErrors(errorString);

May not appear to be as clean, but only needs one function TryToDoSomething, which means less overhead. One doesn't have to repeat operations to check if you can do that thing, or to find the errors that would result if you were to do that thing.

There may be even more ways of doing it, like with try/catch blocks. What are your personal preferences? Is there any consensus on this type of question?

A: 

if it looks like exception you should use try/catch style

if it's true/false (and no evolution in feature) then you may return result flag. returning error string is not so good decidison as far as i can see.

bobrik
If you're parsing user input, wouldn't you want to send them messages about some/all the mistakes they made?
what could deny me to do that with exceptions?
bobrik
You could do that but then you'd only get one exception at a time (I think) which may not be desirable.Also if you use exceptions you are forced to use the try/catch block and can't do either of the other two options.I'd like more of a justification than a do this or that.