user420667
user420667

Reputation: 6700

Stylistic Issue - to separate functions or not?

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?

Upvotes: 1

Views: 105

Answers (1)

bobrik
bobrik

Reputation: 161

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.

Upvotes: 1

Related Questions