Open Closed Principle 💡(Php SOLID Principles)

แชร์
ฝัง
  • เผยแพร่เมื่อ 29 มิ.ย. 2024
  • During part two of our PHP Solids tutorial, we are going to go over the O in SOLID. The Open Closed Principle. This principle states that we must keep our classes open for extension but closed for modification.
    To do this, we must refactor our extensible behavior behind an interface and then flip our dependencies to instead of checking the type and the executing the functionality, simply execute the functionality within the class type and enforce that the functionality exists via an interface that enforces the extensible behavior.
    Come along as we dive into the Open Closed Principle and how to correctly implement it within PHP!
    “When you have a class or method you want to extend without modifying it - separate the extensible behavior behind an interface, and then flip the dependencies”
    ~ Uncle Bob
    What is the open closed principle?
    "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"[Bertrand Meyer-1988]. That is, such an entity can allow its behavior to be modified without altering its source code.
    Describe the open closed principle?
    Meyer's original principle is redefined to refer to the use of interfaces, where multiple implementations could be created and polymorphically substituted for one another.
    • Interface specifications are reused through inheritance; implementation need not be reused.
    • The existing interface is closed to modifications and new implementations must, at a minimum, implement that interface.
    cleancode.studio/series/solid...
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 55

  • @hidayetdogan1348
    @hidayetdogan1348 4 ปีที่แล้ว +13

    The final code of calculate method signature should be calculate(array $shapes) not calculate(Shape $shapes). It works on array of shapes not a single shape.

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว +4

      ☝️☝️☝️☝️
      Thank you Hidayet!
      If the given software language supports passing an interface of arrays, you should do so to properly abide by the Open Closed Principle.
      Php does NOT support passing an enforcing a parameter that is an array where each element must be an instance or implementation of a given interface (at least to the best of my knowledge).
      Just demand the user pass an array instead, or create a function inside of the loop that is responsible for triggering the $shape->area() function and accepts a single shape at a time so we can properly enforce that each shape is an instance that implements the Shape Interface.
      Hidayet Dogan is absolutely correct and officially the pinned comment for this Php Open Closed Principle tutorial.
      Thank you for your feedback Hidayet!

    • @lecturestofallasleepby5977
      @lecturestofallasleepby5977 3 ปีที่แล้ว +2

      @@CleanCodeStudio or better yet calculate(Shape ...$shapes)

  • @forward8229
    @forward8229 9 หลายเดือนก่อน

    Very good and clear explanation. Thank you!

  • @johnsuyang1504
    @johnsuyang1504 4 ปีที่แล้ว +2

    Finally! I understood what open-closed principle means. Power!

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว

      Hey, hey ~ congrats John Suyang! Love comments like this 👊

  • @roonpaul785
    @roonpaul785 4 ปีที่แล้ว +3

    Best explanation I've ever watched on the Open Closed Principle --- THANK YOU!

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว +1

      Thanks Roon Paul :) Glad it was helpful

  • @yosuasasauw4006
    @yosuasasauw4006 2 ปีที่แล้ว

    on this day..i see clearly..! just phenomenal..!

  • @user-ht5jp8rq9s
    @user-ht5jp8rq9s 2 ปีที่แล้ว +1

    So happy to find this tutorial about OCP! The best explanation! Thank u so much)

  • @davidbraxton2620
    @davidbraxton2620 4 ปีที่แล้ว +6

    Absolutely Phenomenal explanation! Thank you man, keep these up ~ your PHP tutorials are stellar!

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว +7

      Thanks David! Glad to help out :) I'm stoked about this PHP SOLID Principles series.
      The Open Closed Principle (more so than any other solid principles in my opinion) is misunderstood. So many developers out there forget that you need to not only flip the dependencies to the class, but you also have to enforce that the extensible behavior that utilizes those dependencies is enforced through an interface (AKA a contract forcing classes to have methods or specific behavior).
      It's so, so important and so, so often forgotten within software design and implementing design principles for the sake of SOLID architecture!
      Software is the art of handling complexity, and handling complexity has one obstacle ~ managing dependencies.
      Design principles, especially SOLID or specifically PHP SOLID design principles do so much for achieving this goal of managing dependencies within software.
      SOLID principles are invaluable when building well architected applications within the Objected oriented paradigm.
      PHP Objected Oriented Design Principles ~ Know them people!
      They're INCREDIBLE and you'll love you're lives and jobs so much more once they click (Apologies for the rant David, I'm a bit passionate about design principles lol :)

    • @davidbraxton2620
      @davidbraxton2620 4 ปีที่แล้ว +5

      ​@@CleanCodeStudio Hahah, no worries dude. Appreciate the quick response and your insight on PHP object oriented design principles.
      "Software is the art of handling complexity, and handling complexity has one obstacle ~ managing dependencies."
      Keep it up! I'm an official subscriber

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว +4

      Will do David, thanks for the subscription and comment ~ feedback is invaluable with these videos!
      I'm looking to get the video on the next Object Oriented Design Principles Video ~ Solid (PHP) - Liskov's Substitution Principle ~ completed and published sometime later this week :)

  • @fsnomaan
    @fsnomaan 4 ปีที่แล้ว +4

    hi jak, great job, keep it up. I am waiting for the rest 3 from SOLID principles video tutorials. hope we will get that soon. Many thanks.
    Feda..

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว +1

      Hoping to get it completed this weekend, but if not Liskov's substitution Principle will definitely be out by the time January comes around!
      I've been doing a lot of research (Especially on pre-conditions and post-conditions) and am extremely excited about going over the L in SOLID :)

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว +3

      Liskov Substitution Principle Php Solid Lesson is out Feda :)
      th-cam.com/video/fSfNwI6mP0g/w-d-xo.html

  • @lecturestofallasleepby5977
    @lecturestofallasleepby5977 3 ปีที่แล้ว +2

    Good Tutorial!

  • @alfredogonzalez8695
    @alfredogonzalez8695 3 ปีที่แล้ว +1

    Best explanation ever! thanks!

  • @letcodeitnow
    @letcodeitnow 3 ปีที่แล้ว +1

    This is really helpful, thanks ❤️

  • @MichelVersianiDev
    @MichelVersianiDev 3 ปีที่แล้ว +1

    Helped a lot , thanks!

  • @danielbaldwin8871
    @danielbaldwin8871 4 ปีที่แล้ว +1

    I see in Uncle Bob's example which is in C:
    void
    DrawAllShapes (Shape* list[], int n)
    {
    for(int i=0; iDraw();
    }
    }
    He is passing in a list of objects with type Shape as well.

    • @CleanCodeStudio
      @CleanCodeStudio  3 ปีที่แล้ว

      In C++ that'll work, in Php you technically can't reference an array of a given type (hopefully they change this soon).
      foreach (Shape $shapes as $shape) {} // breaks in php
      // works in Php
      function draw (Shape $shape)
      {
      $shape->draw();
      }
      foreach ($shapes as $shape)
      {
      draw($shape);
      }

    • @danielbaldwin8871
      @danielbaldwin8871 3 ปีที่แล้ว +1

      @@CleanCodeStudio Thanks. So $shapes is an array of objects with a method draw in them?

    • @CleanCodeStudio
      @CleanCodeStudio  3 ปีที่แล้ว

      ​@@danielbaldwin8871 Correct. The only reason we add a function inside our loop is so we're able to type hint our "Shape" interface.
      By type hinting our interface, we are confirming with absolute certainty that every element in the array implements the Shape interface. The Shape interface demands that any of its implementations have the "draw" method.
      ===================
      Unlike C++ and similar languages, Php can NOT confirm EVERY element in an array is of a given type using type hints. We Can not confirm every array element implements a given interface within a method signature
      |------------------------------|
      DrawAllShapes (Shape* list[], int n) {
      list[n]->draw();
      }
      Inside of Php, you need to add an extra step to confirm that a single element is implementing the interface.
      |-----------------------|
      function draw (Shape $shape) {
      $shape->draw();
      }
      foreach ($shapes as $shape) {
      // Then, we confirm that each element in the array is an implementation of our Shape Interface one at a time by using our draw function.
      draw($shape);
      }
      ===============
      It's a bit of an extra step, but the good news is that *Php 7.4* added *arrow functions*. Using *array_walk* and Php 7.4 *arrow functions* we
      can simplify this into a single line of code.
      *Example*
      |------------------------|
      array_walk($shapes, fn (Shape $shape) => $shape->draw());
      Is Equivalent To:
      |-----------------------|
      function draw (Shape $shape) {
      $shape->draw();
      }
      foreach ($shapes as $shape) {
      draw($shape);
      }
      =====================
      Within php 7.4 and up, you can confirm that an array of elements are all of the same type like this.
      array_walk($list, fn (Type $item) => $item);
      array_walk doesn't return anything, its equivalent to forEach, except the body of each iteration is replaced with a callback function. That callback function can have type hints. This simplifies the Open Closed Principle in Php :)
      That was a lot, let me know if you have any questions!

    • @danielbaldwin8871
      @danielbaldwin8871 3 ปีที่แล้ว

      @@CleanCodeStudio Thanks. That is helpful. What about how to build the array of objects. When you add a new shape do you recommend instantiating it and added it to the array and then loop over it using array_map or array_walk with closure function?

    • @CleanCodeStudio
      @CleanCodeStudio  3 ปีที่แล้ว

      ​@@danielbaldwin8871
      You can get the shapes array from anywhere and create anyway you feel is best given the context of your project.
      As long as an array of elements is passed in to array_walk and use typehint the "ShapeInterface" in the callback you're solid.
      If any of the elements in the array don't implement the ShapeInterface then the application won't run and the exception thrown will show a message telling you that the given element in the array must be an implementation of the ShapeInterface.
      All of these examples work, you'll still be following the open closed principle.
      -----
      $triangle = new Triangle;
      $square = new Square;
      $circle = new Circle;
      array_walk([$triangle, $square, $circle], fn (ShapeInterface $shape) => $shape->draw());
      -----
      array_walk([
      new Triangle,
      new Square,
      new Circle
      ], fn (ShapeInterface $shape) => $shape->draw());
      ---
      $shapes = [
      new Triangle,
      new Square,
      new Circle
      ];
      array_walk($shapes, fn (ShapeInterface $shape) => $shape->draw());
      ---
      $triangle = new Triangle;
      $square = new Square;
      $circle = new Circle;
      $shapes = [$triangle, $square, $circle, $circle, $triangle, $square];
      array_walk($shapes, fn (ShapeInterface $shape) => $shape->draw());

  • @nurhossainsakil9904
    @nurhossainsakil9904 2 ปีที่แล้ว

    do you check your code is working or not? how can you sure it works without running the code?

  • @wayslow
    @wayslow 4 ปีที่แล้ว +2

    Great vid, but get a lav mic and hook it up to a phone (can be old since new ones don't have mini jack ports).Lav mics are cheap (Boya BY-LM10 is good bang for the buck) but sound much better.

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว +4

      Thanks for the tip @Wayslo. Audio and overall sound quality is actually something I've been wanting to read up on and learn a little bit more about for these tutorials.
      Do you have any tips or links you could point me to? I invested in some updated audio gear, but the room I record in doesn't have anything set up for acoustic quality.
      As far as I can tell, the microphones I have (One for face sections of the video another for the coding section) are descent quality. I'm thinking I just have to learn more about properly setting up my environment and editing software properly so the audio quality is better.
      Here's the mic I connect to my mac during the coding sections.
      www.amazon.com/gp/product/B07N53GY3Y/ref=ppx_yo_dt_b_asin_title_o09_s00?ie=UTF8&psc=1
      Here's the mic I connect to my phone during video recordings (It's actually a Lav mic, but the version is MAONO AU100)
      www.amazon.com/gp/product/B01M4J5WCM/ref=ppx_yo_dt_b_asin_title_o09_s00?ie=UTF8&psc=1
      Any advice you'd have to offer would be greatly appreciated ~ I'm still pretty new to all of this and audio is definitely a weak point I want to improve ASAP.

    • @wayslow
      @wayslow 4 ปีที่แล้ว +1

      @@CleanCodeStudio Damn, just to clarify, I was talking about the intro part - coding is fine. You might consider having either the first mic on a boom just outside the frame, or lav mic on you.

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว +4

      Thanks for the tips @@wayslow. I went with the boom mic in this video (tried the lav mic, but decided on editing over the boom mic). I'll give the lav mic a try on the next go around and see if that cleans things up audio wise.

  • @JirsonT
    @JirsonT 4 ปีที่แล้ว +1

    What if you have to execute "only one" type of shape depending of a enum type

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว

      Design principles are best practices to strive for, not absolute laws.
      If you have a single dependency ("only one" type) and are confident that the dependencies for this assertion of code won't rise later in your project time, then I recommend you use a ternary or an if statement.
      Although design principles and architecture is important, design principles are ultimately meant to better manage complexity -- managing complexity is ultimately an engineers job.
      Considering the context of the situation, if adding the design principle will forever make the application more complex then don't use it.
      That being said, if right now it makes your application more complex --- yet, later in the future you may need to extend the behavior ultimately easing the complexity of your application when the principle is implemented then use it.
      At the end of the day Love, Care, & Attention To Specific Details are the most important software practice.
      Design principles are another tool in your belt, that you are able to reach on often but if it will only make your application more complex -- then, don't use the principle.
      -----
      Biggest Take Away: Design principles are goals to strive towards, not absolutions. Your love, care, and dedication towards the small details is most important skill & outweighs design principles given you understand the pros and cons of your choice to use or not use the given principle.

  • @danielbaldwin8871
    @danielbaldwin8871 4 ปีที่แล้ว

    I don't understand how your code will work. Are you passing in for example an instance of the Circle object when you call the calculate method? If you are, then how can you do a foreach on the single shape. You either don't need the foreach or you are somehow passing in an array of Shape objects. In which case PHP, I would think, would throw a type mismatch error because the array is not of type Shape. Can you please show me how you are calling the calculate method and what you are passing it from the outside? Thanks

    • @CleanCodeStudio
      @CleanCodeStudio  3 ปีที่แล้ว

      Anyone seeing this comment, the thread answering this question is directly above (Thanks for the great questions on the Open Closed Principle example in Php in comparison to C++ Daniel :)

  • @stormybear4986
    @stormybear4986 ปีที่แล้ว

    It looks to me like when you flip the dependencies you are now violating the 1st principle SRP. Can you clarify?

    • @CleanCodeStudio
      @CleanCodeStudio  ปีที่แล้ว

      The opposite I believe, By depending on the interface you're inverting dependence from the multiple file classes and instead depending on the single fact that it is of type file.
      You only depend on the fact that it is a file, not what kind of file or how the file handles the actual parsing or download functionality.
      As long as it has that method defined in the file interface, then it is a file type - and that single fact is what you depend on.

  • @timfennis91
    @timfennis91 4 ปีที่แล้ว +2

    It really bothers me that you didn't call it a rectangle.

    • @CleanCodeStudio
      @CleanCodeStudio  4 ปีที่แล้ว +1

      In hind sight, I should've used Rectangle...it honestly bothers me too
      ¯\_(ツ)_/¯

  • @Paltibenlaish
    @Paltibenlaish 3 ปีที่แล้ว +1

    it is the same example from laracast..... :////

    • @CleanCodeStudio
      @CleanCodeStudio  3 ปีที่แล้ว

      Laracasts and just about every SOLID Principles book you'll ever read :)
      SOLID Principle examples are pretty ubiquitously used.
      That being said, I point out in several lessons that Laracasts is where I learned a lot of my software experience and highly recommend Laracasts as a worth while membership to invest in.
      If you go to Clean Code Studio's TH-cam page you'll even see the Laracast's TH-cam channel as one of our recommended youtube channels.
      There's no doubt that a lot of my lessons are inspired by Laracast's due to no other reason than Laracast's being the BEST resource for learning Php and and real world modern web development.
      Anyone reading this, subscribe to laracasts.com.
      $15/month to subscribe to laracasts and access the teachings of Jeffrey Way ~ in my opinion the best software engineering teacher on the web and most likely on this blue spinning ball we call earth for modern Php web development :)
      Some of our lessons, that I feel like I can add value to, are directly inspired by laracasts and I make it a point to point that out.
      I only use Laracast's examples when I feel like I can add unique value not added via Laracast's.
      This wasn't an example I conscientiously used from Laracasts, but sometimes I do unintentionally use laracasts examples simply due to Laracast's being my primary learning source for several years.
      Any lessons you feel like are laracasts examples that I didn't notice were the same examples from laracasts that don't add any unique value in your opinion - please, point out that they are laracasts inspired.
      Again, I am very very thankful for laracasts and Jeffrey Ways and do my best to point out when my examples are from Laracasts but have personally watched 100's of hours worth of learning content from laracasts and sometimes use examples that I learned a long time ago but don't remember exactly where from.
      I hope that clears things up a bit, the last thing I ever want to do is discredit such a valuable content creator and teacher like Jeffrey Ways. I have the utmost respect and gratitude for what he does and the way in which he teaches me and consider him my biggest role model for the way in which I both create software every single day and teach software through this channel.

    • @arunabraham9382
      @arunabraham9382 3 ปีที่แล้ว

      This is just a general explanation may uses. There are other examples out there like Payments. or any generalized functionalities

  • @SocialDanceProject
    @SocialDanceProject 3 ปีที่แล้ว +1

    Can I buy you a microphone please :))

    • @CleanCodeStudio
      @CleanCodeStudio  3 ปีที่แล้ว

      Appreciate it friend, but we did that audio upgrade almost a year back now ~ I'd bet you'd like the newer Clean Code Studio screen-casts. The content was solid back on these screen-casts, but the editing and recording quality was lack-luster for-sure. Hopefully I'll get back around to re-recording SOLID principles one of these days, just all about finding that time.

  • @QueeeeenZ
    @QueeeeenZ 2 ปีที่แล้ว

    Very bad sound, please get a better microphone.

    • @CleanCodeStudio
      @CleanCodeStudio  ปีที่แล้ว

      You are not wrong, upgraded a couple years back