Aren't Information Expert & Tell Don't Ask at odds with Single Responsibility Principle?

前端 未结 6 1532
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 12:36

Information-Expert, Tell-Don\'t-Ask, and SRP are often mentioned together as best practices. But I think they are at odds. Here is what I\'m talki

6条回答
  •  无人及你
    2020-12-25 13:28

    DTOs with a sister class (like you have) violate all three principles you stated, and encapsulation, which is why you're having problems here.

    What are you using this CustomerDTO for, and why can't you simply use Customer, and have the DTOs data inside the customer? If you're not careful, the CustomerDTO will need a Customer, and a Customer will need a CustomerDTO.

    TellDontAsk says that if you are basing a decision on the state of one object (e.g. a customer), then that decision should be performed inside the customer class itself.

    An example is if you want to remind the Customer to pay any outstanding bills, so you call

      List bills = Customer.GetOutstandingBills();
      PaymentReminder.RemindCustomer(customer, bills);
    

    this is a violation. Instead you want to do

    Customer.RemindAboutOutstandingBills() 
    

    (and of course you will need to pass in the PaymentReminder as a dependency upon construction of the customer).

    Information Expert says the same thing pretty much.

    Single Responsibility Principle can be easily misunderstood - it says that the customer class should have one responsibility, but also that the responsibility of grouping data, methods, and other classes aligned with the 'Customer' concept should be encapsulated by only one class. What constitutes a single responsibility is extremely hard to define exactly and I would recommend more reading on the matter.

提交回复
热议问题