jeudi 26 mars 2015

How much can object know about other object? Is it example of demeter's law violation?

I've got an issue with understanding how well can I allow objects to know each other.


In my simple example I've got classes: Bill, Customer, Checkout and Cart. Customer has list of their bills, cart is associated to customer and checkout finalize buying operation (add bill to customer)


SO in method public void checkouts(Cart cart) I initliaze new bill Bill bill = new Bill(cart) and then I want to add bill to the customer. I've got 3 possible ways to do it:



cart.getCustomer().getBills().add(bill);
// ^^^ directly add bill to ArrayList in Customer
cart.getCustomer().addBill(bill);
// ^^^ Customer get bill and put it itself in their own method
cart.addBillToCustomer(bill);
// ^^^ In this example class Checkout doesn't now anything about customer.
// Responsibility goes to cart which calls getCustomer().addBill(bill)


I guess the first one is really wrong because Checkout has to know that getBills() returns array list(which is dangerous)


In the second example class checkouts gets customer which isn't directly associated with it and than it has to know customer interface to add bills.


In third example checkout, which isn't directly associated with customer, don't use any knowledge about customer it just delegate task to cart which is directly connected to customer (it has field Customer customer)


Which solution is the best,why and why others are worse?


Aucun commentaire:

Enregistrer un commentaire