views:

104

answers:

3

Generally, I try and avoid using inheritance in WCF contracts, preferring composition.

But in the following situation...

  • I have a service operation that can result in one of two things: ResultA and ResultB.
  • There is a boolean/enum in the response message to report this outcome.
  • There are a number of other properties in the response message. Some of these are only relevant in the event of ResultA and some are only relevant in the event of ResultB.

I see my options as being:

  1. Have a single response message contract that contains everything and when properties are not relevant, they are left as null. The client then has to look at the bool/enum to see if its ResultA or ResultB and ignore properties accordingly.
  2. Have 2 response messages contracts, both inheriting from a shared base. One representing ResultA and its relevant properties and one representing ResultB and its relevant properties.

I much prefer option 2 for a number of reasons, but it breaks the composition over inheritance rule.

What do people think?

A: 

All rules are meant to be broken. If you are reusing objects and the systems allows you to use inheritance... why not use it? As Phil Haack puts it... think for yourself.

Limiting yourself by a set of artificial rules is a great way to make you work much more difficult. There is a reason we can use inheritance, and I say this is one of them.

Prefer Composition Over Inheritance (Steve Rowe) Here is another angle. But if you read it he is talking about the reuse of function, not data.

Matthew Whited
+1  A: 

My gut feeling here is "redesign your interface". Having methods with dubious return types is generally not a sign of good design. This leads to a lot of unnecessary and error-prone logic in every caller of the method.

So I would suggest "secret option number 3": refactor the interface into two separate methods.

d91-jal
A: 

Prefer composition over inheritance != Never use inheritance :-)

Michael Wiles