DEV Community

Cover image for Demeter Law
DevByJESUS
DevByJESUS

Posted on

Demeter Law

Just Look at The Example Below The difference between the two if Condition

Do Not Do This

 private final List<Carriage> carriages [...]
 private int percentReservedBarrier = 70;
 public void reserveSeats(ReservationRequest request) {
   for (Carriage carriage : carriages) {
     if (carriage.getSeats().getPercentReserved() < 
                                  percentReservedBarrier) {
     request.reserveSeatsIn(carriage);
     return;
    }
  }
 request.cannotFindSeats();
}
Enter fullscreen mode Exit fullscreen mode

Do This Instead

public void reserveSeats(ReservationRequest request) {
 for (Carriage carriage : carriages) {
  if 
  (carriage.hasSeatsAvailableWithin(percentReservedBarrier)) 
  {
   request.reserveSeatsIn(carriage);
   return;
  }
 }
 request.cannotFindSeats();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)