mituri

SOLID Open/Closed principle

Feb 14th, 2021
875
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Open/Closed principle */
  2. /* open for extensions, close for modification */
  3. /* the problem is we cant add new ice cream flavor without editing iceCreamFlavorsArray */
  4. /* we can easly fix that adding addFlavor function*/
  5.  
  6. /* BAD */
  7. const iceCreamFlavors = ["chocolate", "vanilla"];
  8. const iceCreamMaker = {
  9.     makeIceCream(flavor) {
  10.     if (iceCreamFlavors.includes(flavor)) {
  11.         console.log("You have a ice cream.")
  12.     } else {
  13.         console.log("no ice cream for you.")
  14.     }
  15.   }
  16. }
  17.  
  18. iceCreamMaker.makeIceCream("chocolate")
  19. iceCreamMaker.makeIceCream("banana")
  20.  
  21. /* GOOD */
  22. const iceCreamFlavors = ["chocolate", "vanilla"];
  23. const iceCreamMaker = {
  24.     makeIceCream(flavor) {
  25.     if (iceCreamFlavors.includes(flavor)) {
  26.         console.log("You have a ice cream.")
  27.     } else {
  28.         console.log("no ice cream for you.")
  29.     }
  30.   },
  31.  
  32.   addFlavor(flavor) {
  33.     iceCreamFlavors.push(flavor)
  34.   }
  35. }
  36.  
  37. iceCreamMaker.addFlavor("banana")
  38. iceCreamMaker.makeIceCream("banana")
  39.  
Advertisement
Add Comment
Please, Sign In to add comment