Lightman
Lightman

Reputation: 1265

Should I create a separate DTO class for each Service method?

There is a Service to work with a Customer entity.

Service already implements a GetCustomer method which returns a CustomerDTO.

Service must implement methods to change Customer's Phone, Address, SalesManager and Discount. Customer is allowed to change only Phone and Address, Sales Director is allowed to change only Customer's SalesManager, while Sales Manager is allowed to change only Customer's Discount.

  1. Should I create only one service method ChangeCustomer?
    • Should I use CustomerDTO which I used as a return type in GetCustomer method, e.g. ChangeCustomer(CustomerDTO)?
    • Should I use some other CustomerChangeDTO, e.g. ChangeCustomer(CustomerChangeDTO)?
  2. Should I create several service methods ChangeCustomerPhone, ChangeCustomerAddress, ChangeCustomerManager and ChangeCustomerDiscount?
    • Should I use CustomerDTO in each of these service methods, e.g. ChangeCustomerName(CustomerDTO), ...?
    • Should I user a separate DTO class in each of there service methods, e.g. ChangeCustomerName(CustomerNameChangeDTO), ...?
  3. Maybe some other set of service methods?

It seems that a single DTO class makes service much easier to use on client, because all client has to do is to request CustomerDTO, change some of it's properties and send back. Service is to process all changes in CustomerDTO and apply business logic to real Customer entity and maybe other entities.

Are there any other pros / cons for each variant?

Upvotes: 3

Views: 1299

Answers (1)

Jakub Lortz
Jakub Lortz

Reputation: 14904

Your WCF service is in the application layer, so it should have a separate method for every use case. You clearly have 3 use cases here:

  1. Customer can change Phone and Address
  2. Sales Director can change SalesManager
  3. Sales Manager can change Discount

So your service should expose 3 methods. Each of these methods will not only have to update Customer entity, it will have to check permissions first. If you try to implement it in 1 method, you will end up with a lot of ifs and unclear behavior. For example what to do if a Sales Manager tries to change Discount and Phone? Ignore the Phone? Throw an exception?

Each method should use a different DTO, containing only properties necessary for the method. (Btw, you can change 'DTO' to 'Command' in the class names - for example ChangeCustomerDiscountCommand. Looks nicer than 'DTO').

If you use a single DTO, it will be confusing for the client (Why are there other properties in the class? What will happen if I leave them empty? What will happen if I change them? etc.)

Upvotes: 3

Related Questions