4. Law of Demeter
● Each unit should have only limited knowledge about other units:
only units "closely" related to the current unit.
● Each unit should only talk to its friends; don't talk to strangers.
● Only talk to your immediate friends.
5. Mockito.mock()
@Test
public void lawOfDemeterBroken(){
Person gnan = mock(Person.class);
Pants pants = mock(Pants.class);
Wallet wallet = mock(Wallet.class);
Collection<Bill> bills = mock(Collection.class);
Bill bill = mock(Bill.class);
Iterator<Bill> iterator = mock(Iterator.class);
// …
7. Law of Demeter: broken
// ...
Person dennis = new Person();
borrow(gnan, dennis, 5);
assertTrue(dennis.getPants().getWallet().getBills().contains(bill));
}
8. Law of Demeter: broken
public static void borrow(Person from, Person to, int amount){
Iterator<Bill> iterator = from.getPants().getWallet().getBills().iterator();
while (iterator.hasNext()) {
Bill bill = iterator.next();
if(bill.getValue() == amount){
iterator.remove();
to.getPants().getWallet().getBills().add(bill);
break;
}
}
}
9. Law of Demeter: fixed
@Test
public void lawOfDemeter(){
Person gnan = mock(Person.class);
when(gnan.removeMoneyAmount(anyInt())).thenReturn(new Bill(5));
Person dennis = new Person();
dennis.borrow(5, gnan);
assertEquals(5, dennis.getMoneyTotal());
}
11. Law of Demeter
public String methodChain(){
StringBuilder builder = new StringBuilder();
builder.append("this")
.append("doesn't")
.append("break")
.append("encapsulation");
return builder.toString();
}