Skip to content

Commit caa2724

Browse files
committed
Added SRP example.
1 parent 9191067 commit caa2724

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

README.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,56 @@ print(person.name_as_first_and_last) # => ["Ryan", "McDermott"]
740740
## **Classes**
741741

742742
### **Single Responsibility Principle (SRP)**
743+
744+
We create a class called `Burglar`, which has a method called `steal`. This method breaks the **SRP** because it doesn't just steal. It also puts on and removes the invisibility cloak, which might lead to all sorts of issues for the burglar.
745+
746+
```python
747+
class Burglar:
748+
def __init__(self):
749+
self._artifacts = []
750+
751+
def steal(self, artifact: str):
752+
print("Putting on the invisibility cloak.")
753+
print("Taking the artifact.")
754+
self._artifacts.append(artifact)
755+
print("Removing the invisibility cloak.")
756+
757+
bilbo = Burglar()
758+
bilbo.steal("Arkenstone")
759+
```
760+
761+
A better way would be to create separate methods that can be called when appropriate.
762+
763+
```python
764+
class Burglar:
765+
def __init__(self):
766+
self._artifacts = []
767+
768+
def steal(self, artifact: str):
769+
print("Taking the artifact.")
770+
self._artifacts.append(artifact)
771+
772+
def cloak(self):
773+
print("Putting on the invisibility cloak.")
774+
775+
def remove_cloak(self):
776+
print("Removing the invisibility cloak.")
777+
778+
779+
bilbo = Burglar()
780+
bilbo.cloak()
781+
bilbo.steal("Arkenstone")
782+
bilbo.remove_cloak()
783+
```
784+
785+
Now Bilbo can put on the cloak, walk in, steal the Arkenstone, walk out, so he won't be seen by Smaug and remove the cloak.
786+
787+
Example taken from:
788+
789+
https://codingwithjohan.com/blog/python/solid-single-responsibility-principle/
790+
791+
792+
743793
### **Open/Closed Principle (OCP)**
744794
### **Liskov Substitution Principle (LSP)**
745795
### **Interface Segregation Principle (ISP)**

0 commit comments

Comments
 (0)