Is it bad practice to have an output parameter in a method in a WCF service?

Duncan Edwards picture Duncan Edwards · Jan 19, 2011 · Viewed 12.2k times · Source

I'm looking for reasons beyond the usual "out parameters are confusing and indicate the method is doing more than one thing"-style arguments and more about what is specifically bad about output parameters in WCF services. Where I work now, we have a rule against them in WCF services, and I'm trying to work out why!

Answer

Joe B. picture Joe B. · Jan 19, 2011

Personally, I use out parameters in specific places (such as methods named TryParse()). So, I have some of the bias you talked about where I only use it in specific, limited places. In addition, you can't assume that a .Net application is going to be consuming this on the other end. Because WCF provides an interface consumable as a SOAP or REST web service (among other communication types), I can't guarantee that WCF would even support out params for compatibility with non-.Net consumers.

Beyond that, a WCF service is providing an API to a consumer, and API's should provide an interface that should be consumed with limited knowledge of how the server methods were coded. (Don't presume the guy writing the WCF server is the same guy writing the client on the other end). Attempting to use an out param on an API seems like a code smell. Presumably, one would use an out param to return another value(s) to the consumer. Consider instead using a message object. A message object is specifically composed of all the pieces of data that need to be sent from the WCF server to its consumer. For example, let's say you have a method exposed in a WCF server called TryCreateUser:

bool TryCreateUser(string name, string email, out User user){}

where you intend to return a bool indicating where user creation occurred successfully and a User object containing the user if it succeeded. I would create a new class, UserCreationMessage:

class UserCreationMessage {
    bool IsSuccessful;
    User user;
}

Return this message object back to the consumer, and you can still get the multiple returned values. However, you now have a coherent object being returned that's more explanatory to the end user of the API.

In the end, I'd reason that it's bad practice to have an out parameter in an API, such as a WCF server because programmers creating the consumer for this service have to be able to easily look at the API and consume it without jumping through the hoops that an out param present. Since a better design for this exists, use it. API's require higher coding standards, especially in the interface exposed to the end consumer.