Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. // Original Code
  2. public function makeBooking($cargo, $voyage)
  3. {
  4. // This is an over-simplification of the logic for determining if a ship is over-booked
  5. $maxBooking = $voyage->getCapacity() * 1.1;
  6. if ($voyage->getBookedCargoSize() + $cargo->getSize() > $maxBooking) {
  7. return false;
  8. }
  9. return $voyage->addCargo($cargo);
  10. }
  11.  
  12. // Alternative 1: Create a private method, or a method on the entity.
  13. public function makeBooking($cargo, $voyage)
  14. {
  15. $maxBooking = $this->getMaxBookingSize($voyage);
  16. if ($voyage->getBookedCargoSize() + $cargo->getSize() > $maxBooking) {
  17. return false;
  18. }
  19. return $voyage->addCargo($cargo);
  20. }
  21.  
  22. private function getMaxBookingSize($voyage)
  23. {
  24. // This is a simplification of the logic for determining if a ship is over-booked
  25. if ($voyage->isDomestic()) {
  26. return $voyage->getCapacity() * 1.2;
  27. }
  28. return $voyage->getCapactiy() * 1.1;
  29. }
  30.  
  31. // Alternative 2: Use a Policy class to keep the business logic explicit and easy to find / update
  32. class BookingPolicy
  33. {
  34. public function isAllowed($cargo, $voyage)
  35. {
  36. // This is a simplification of the logic for determining if a ship is over-booked
  37. if ($voyage->isDomestic()) {
  38. $maxBooking = $voyage->getCapacity() * 1.2;
  39. } else {
  40. $maxBooking = $voyage->getCapactiy() * 1.1;
  41. }
  42. return $voyage->getBookedCargoSize() + $cargo->getSize() > $maxBooking);
  43. }
  44. }
  45.  
  46. public function makeBooking($cargo, $voyage)
  47. {
  48. if ($bookingPolicy->isAllowed($cargo, $voyage) {
  49. $voyage->addCargo($cargo);
  50. } else {
  51. return null;
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement