Search code examples
c#servicedataprovider

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?


Solution

  • 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.