Too Many [out] Parameters (.NET)
When a method contains out parameters, especially when there are more than one out parameter, consider returning a class instead.
// Uses a bool to signal success, and also returns width and height.
bool GetCoordinates( MyObject element, out int width, out int height )
Replace with a single return parameter, or perhaps a single out parameter.
bool GetCoordinates( MyObject element, out Rectangle coordinates )
Alternatively you could return a null reference. Bonus points if the class implements the Null Object pattern. This allows you to get rid of the boolean as the class itself can signal a valid state.
Rectangle GetCoordinates( MyObject element )
Further, if it makes sense, have a specialised class for the return value. While not always applicable, if the return value is not a simple true/false for success then it may be more appropriate to return a composite of the returned object plus state. It makes caller's code easier to read and maintain.
class ReturnedCoordinates
{
Rectangle Result { get; set; }
CoordinateType CoordinateType { get; set; }
GetCoordinateState SuccessState { get; set; }
}
ReturnedCoordinates GetCoordinates( MyObject element )
Admittedly overuse of this can lead to further bad smells.
A Good [out] Pattern
Note that [out] parameters are still useful, especially in the following Tester-Doer pattern.
// In the Int32 class.
bool TryParse(string toParse, out int result)
this is far more efficient than
// BAD CODE - don't do this.
int value = 0;
try
{
value = int.Parse(toParse);
}
catch {}
when you expect the input string toParse
is probably not valid.
Summary
In many cases, the presence of any [out] parameters indicates a bad smell. Out parameters make the code harder to read, understand, and maintain.