1

我正在设置一个由多个 WCF 服务组成的应用程序,其中只有一个可以访问数据库。我们将在 DTO 中传递大量数据,有时是批量传递。因为批量操作假设一个参数保持不变,所以我喜欢以下模式:

private void UpdateItems(long clientId, ItemDto[] items);

不过,根据Martin Fowler的说法,DTO 被定义为“可以保存调用的所有数据”的对象。这是否意味着我不应该在 DTO 之外传递其他数据?我真的应该看下面这样的模式吗?似乎打败了我的参数点。

private void UpdateItems(ItemsDto itemsDto);

ItemsDto {
    long ClientId;
    ItemDto[] Items;
}
4

1 回答 1

3

I think Martin Fowler is great, but definitely don't want to do anything "because Fowler said". What is really needed, is to think about why he gave that advice, and see if those reasons apply for you.

The effect of creating a multi-item DTO here would be to protect yourself from needing to change the interface if you need to change the arguments for batch operations.

For example, if you have to add clientTimeStamp to your parameters, it either looks like this:

private void UpdateItems(long clientId, DateTimeOffset clientTimeStamp, ItemDto[] items);

or this:

private void UpdateItems(ItemsDto itemsDto);

ItemsDto {
    long ClientId;
    DateTimeOffset clientTimeStamp;
    ItemDto[] Items;
}

Also, notice that you can still use your old interface in a day-to-day way by creating an extension method that packs the arguments into your DTO.

So what's the benefit? The difference is that if your methods are public and used by many clients, you can maintain backwards compatibility the second way. It's also a bit easier to change your code, though with VS and resharper, it doesn't actually make much difference. The cost is a some amount of additional code to write (fairly small in the example, but probably larger in your real codebase).

If you expect to have client code outside your direct control (including clients you write but may not be able to update for some reason), a DTO here is probably worth the cost. Otherwise, I would leave it alone until next time I wanted to add a parameter there.

于 2013-02-24T14:17:31.623 回答