principlecsharpMajor
Using return value vs out parameters
Viewed 0 times
returnvalueusingparametersout
Problem
It's very popular to see code like this:
You can't understand the result of this method by looking at its name (it could actually be a
What's the best approach to refactor such kind of methods? What I have in mind is something like this:
What do you think?
EDIT
It seems that so many people prefer
rather than
But what if a method is going to have a result instead of being
bool DoSomething([some arguments]);You can't understand the result of this method by looking at its name (it could actually be a
void).What's the best approach to refactor such kind of methods? What I have in mind is something like this:
void DoSomething([some argumens],out bool everythingIsOk);What do you think?
EDIT
It seems that so many people prefer
bool TryDoSomething();rather than
void DoSomething(out bool success);But what if a method is going to have a result instead of being
void? Can we use int.TryParse pattern or we should return the result and throw an exception if something goes wrong?Solution
You’re asking the wrong question. In reality, both methods are bad. If you need the success message, either throw an exception on failure (but only if this is really an exceptional scenario, or return the success and indicate this in the method name. For instance, by calling the method
In general, your example sounds like the method is actually doing two distinct things, otherwise there would be no confusion in the first place. But this is code smell anyway: every method should have only one purpose. If that is the case, then the meaning of the return value is always clear, no need to give it a name.
TrySomething.In general, your example sounds like the method is actually doing two distinct things, otherwise there would be no confusion in the first place. But this is code smell anyway: every method should have only one purpose. If that is the case, then the meaning of the return value is always clear, no need to give it a name.
Context
StackExchange Code Review Q#9274, answer score: 24
Revisions (0)
No revisions yet.