![]() We have a Rectangle class that contains the data for a rectangle, and a Board class that is used as a collection of Rectangle objects. class Rectangle():Īrea += item.get_height() * item.get_width() Essentially meaning that classes should be extended to change functionality, rather than being altered into something else.Īs an example, take the following two classes. In the open/closed principle classes should be open for extension, but closed for modification. We now have only one reason to change the Page class. import jsonĭoing this means that if we wanted to create an XML format we could just add a class called XmlPageFormatter and write some simple code to output XML. We then create a secondary class called JsonPageFormatter that is used to format the Page objects into JSON. This is fine for a class as simple as this, but if it contained more properties then the formatting would be more complex to change.Ī better approach to this is to modify the Page class so that is only knows about the data is handles. What happens, however, if we want to change the output of the JSON string, or to add another type of output to the class? We would need to alter the class to either add another method or change an existing method to suit. ![]() This might seem like a good idea as the class is responsible for its own formatting. We can also use a method in this class called format_json() to return the page as a JSON string. This class knows about a title property and allows this title property to be retrieved by a get() method. Taking an example of the (simple) class called Page. This states that a class should have a single responsibility, but more than that, a class should only have one reason to change. SOLID is an acronym that stands for the following: For more explanation about Metaclasses see the interface section in the basics of getting started with object oriented programming in Python article. I should also note here that Python doesn't really have an interface system so I have used Metaclasses to create the needed situations. If you are familiar with only PHP or Python then this will be a good learning resource on learning the other side. I originally wrote about SOLID principles with PHP as the basis of the article, but as the lessons here can be easily applied to any object oriented language I thought that I would re-write it with Python in mind. The SOLID principles apply to any object oriented language, but I'm going to concentrate on what they mean in a Python application in this post. They were coined by Robert "Uncle Bob" Martin in the year 2000 in his paper Design Principles and Design Patterns. SOLID is a set of object oriented design principles aimed at making code more maintainable and flexible.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |