I see the following code pattern all over the place in my company's codebase (.NET 3.5 application):
bool Foo(int barID, out Baz bazObject) {
try {
// do stuff
bazObject = someResponseObject;
return true;
}
catch (Exception ex) {
// log error
return false;
}
}
// calling code
BazObject baz = new BazObject();
fooObject.Foo(barID, out baz);
if (baz != null) {
// do stuff with baz
}
I'm trying to wrap my head around why you would do this instead of having the Foo method simply take the ID and return a Baz object, instead of returning a value that isn't used and having the actual object be a ref or output parameter.
Is there some hidden benefit of this coding style that I'm missing?
bazbeingnulland the returnedboolbeingfalseare not equivalent.new BazObject()is nevernull, so unlessbazObjectis updated before theExceptionis thrown inFoo, whenfalseis returnedbazwill never benull. It would help tremendously if the spec forFoowere available. In fact, this is perhaps the most serious problem exhibited by this code.