开发者

Delete entities in service layer: Should I foreach a Delete(T item) or call a Delete(List<T> list)?

My 开发者_运维知识库user can delete multiple entities in a DataGrid. Should I create now a DeleteCustomer method in my customerService class

like

Presenter/ViewModel:

public void DeleteCustomers()
{
    foreach(...SelectedCustomers)
    {
        customerService.DeleteCustomer(item);
    }
}

OR

public void DeleteCustomers()
{
  customerService.DeleteCustomers(SelectedCustomers);
 // The DataProvider is enumerating the list...
}

What do you think is better?


You've already answered the question yourself. In deleting a singular customer, you call:

customerService.DeleteCustomer(item);

This indicates that you are passing the items to be deleted back to the service (which here is really an abstraction over a specific way of how to handle customers). You are making a clear indication that the service has the best knowledge as to how to perform this operation.

To that end, deleting multiple customers should be like the latter option:

customerService.DeleteCustomers(SelectedCustomers);

You gain a few benefits here:

  • Your are again acknolwedging that the service knows best how to perform this operation. Perhaps the service (or whatever it's abstracting) can optimize the batch operation in ways that are not available or immediately obvious to consumers of the service.
  • If this is a service/WS/SOA call, then best practices indicate that you should prefer fewer "chunky" calls over frequent light calls.


Is there any reason why the DataProvider shouldn't enumerate the IEnumerable<T>? If not, just use the second way and let the DataProvider take care of it.


I'd go with the second one as that clearly exposes what you want to do.


I would have both methods... if you only need to delete a single customer at some point its annoying having to wrap a single instance in a IEnumerable


Typically in a client-server scenario, you want to minimize the amount of round-trips.

Obviously this means that between enumerating the collection and deleting individually, and deleting the collection at once, the latter is the better choice.

However as an alternative, to reduce the communication even further, you could collect mutations to a collection (Add, Delete, Replace and so on...) and only when the user presses 'Save' for instance, call the service and send over a set of changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜