Question

I have a service contract:

[DataContract]
public class Something
{
    [DataMember]
    public MyEnum SomeEnumMember {get;set;}
}

Some of our devs are doing this sort of thing:

public Something()
{
    SomeEnumMember = MyEnum.SecondEnumValue;
}

I am of the opinion that constructor logic does not belong in our service contracts since that code won't work if you use "Add Service Reference..." and are working with proxy classes generated by Visual Studio.

Internally, we are using Castle DynamicProxy as shown here. However, I would prefer our devs avoid constructor logic in service contract classes in case we can't use DynamicProxy for some reason.

So: does constructor logic have a place in these classes, or as a matter of best practice should we look at them as more of a DTO and implement them with no behavior?

Was it helpful?

Solution

It may only make a difference when creating the objects in the first place to transfer via your services. If you wish to have the default value of your SomeEnumMember to be different when instantiating to be transmitted as a convenience, it may make sense:

var mySomething = new Something();
mySomething.SomeEnumMember = MyEnum.SecondEnumValue; //this line may be omitted if it's set automatically by the constructor
SendData(mySomething);

On the receiving side, it will make no difference as the values (I think, and from your tests) are explicitly set by the sender anyway. Additionally, it will be extra/wasted work by your receivers instantiating/deserializing the objects, but most likely this is a negligible overhead.

In general, your data transfer objects shouldn't contain logic anyway. Perhaps depending on your application architecture if you're using this object in a bunch of places other than just transferring information, it might make sense. Though I would question that architecture: I like to keep the objects concerned with client-server communication abstracted away from the rest of my application architecture. That way I can freely make changes to that (specialized serialization, architecture changes, etc.) without seriously affecting the rest of my application(s).

OTHER TIPS

I agree with you, I don't think constructor logic belongs there and I never actually worked with a wcf that had constructor logic in it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top