You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
+
classBurglar:
748
+
def__init__(self):
749
+
self._artifacts = []
750
+
751
+
defsteal(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
+
classBurglar:
765
+
def__init__(self):
766
+
self._artifacts = []
767
+
768
+
defsteal(self, artifact: str):
769
+
print("Taking the artifact.")
770
+
self._artifacts.append(artifact)
771
+
772
+
defcloak(self):
773
+
print("Putting on the invisibility cloak.")
774
+
775
+
defremove_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.
0 commit comments