DataContracts with behavior

半腔热情 提交于 2019-12-03 13:46:35

You can add all the behavior you want to your data contracts. You should clearly document the fact that the behavior won't be visible to clients, or someone will be disappointed later on. Also document the fact that care must be taken to not add any implementation-dependent data to the data contract, since it's not anything you want to pass to the clients.

All in all, I think you'd be better off to let data contracts be data contracts, and to leave the behavior out of them.

Why can't you create your data contract (MyDataContract) in a classic fashion, just data fields, nothing else, and then derive your behavior class from it?

public class BehaviorialClass : MyDataContract
{
.....
}

That way, you have a nice, clean separation of concerns, your data contract isn't "polluted" by behavior it can't really deal with anyway.....

Marc

A good compromise to putting behavior directly in your DataContracts would be define behaviors as extension methods in either the same assembly as your Contracts or a different assembly entirely. Optionally, extension methods can be placed in a separate namespace from the contracts to further insulate the separation of data and behavior.

That way your Contracts are kept clean but at the same time, .NET consumers of your contracts would have an easy way to import additional functionality relating to those DataContracts.

At some point you're going to want to use MemberwiseClone and implement interfaces without needless intermediary data translation (and even worse, needless MAINTENANCE). Extension methods are for when you literally have no control over the object definition but still need object-oriented fluency; they add busy work in any other situation and scatter class definitions worse than C/C++. Buck the "trends" and do what works for you, you might just discover a pattern that changes the whole ballgame (like Jeffrey Richter's AsyncEnumerator).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!