The Square class should not inherit from the Rectangle class. So what is the correct solution? Not every idea from "reality" should be implemented 1:1 in code. We should not change how the parent class's methods work. Overriding the setWidth() and setHight() methods broke the Liskov substitution rule. But if we replace it, it turns out that the test does not pass (100 != 20). Imagine a BlogPost class:Ĭlass BlogPost Īccording to the Liskov substitution principle, we should be able to replace the Rectangle class with the Square class. Both of these principles, in my opinion, try to say the same. The single responsibility principle should be used together with the "high cohesion and low coupling" principle. Your code should be like Lego blocks, easy to use in different places. The opposite of Lego bricks, they have a low coupling, they can be combined freely and each one can be used anywhere. One puzzle fits only in one place, it cannot be combined with other puzzles. The puzzles are characterized by high coupling. Puzzles and Lego blocks are good examples of that. Your method/class should be like Bob, do one thing.Ĭoupling is about how easy it is to reuse a given module or class. Bob's job is to peel potatoes, nothing else, it’s an example of high cohesion. Each of these steps consists of several others. She needs to make a sponge cake, cream, glaze, cut the fruit and put it all together. A simple example here would be Bob and Alice, the cook's helpers. I will try to present it in simple-to-understand examples.Ĭohesion determines how much a function or class is responsible for. In 1974, the " high cohesion and low coupling" principle was described for the first time in the article Structured Design in the IBM journal. I think we need to use a different object-oriented programming principle to answer this question. Should we set up a separate class for each of these activities? How far do we go with this “single responsibility”?! Perhaps, sending an email can be considered a “one thing”? After all, it consists of many steps such as preparing the e-mail content and subject, extracting the user's e-mail address and handling the response. Other explanations say that a class or a function should do one thing.īut what is this “one thing”? Is user registration can be considered “one thing”? Or maybe it's more "things", because registrations include some other smaller things, password encryption, saving to the database and sending an e-mail. What does it mean? For me, this sentence is not helpful :). Uncle Bob describes it as “ A class should have one, and only one, reason to change”. But seriously, I think it is very important. I think this is the most famous rule (probably because it is the first and some people did not read on). So let's go through the five SOLID principles together.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |