| Conditions | 4 |
| Total Lines | 53 |
| Code Lines | 31 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | import pytest |
||
| 56 | def test_scenario(subject, observer): |
||
| 57 | # The client code. |
||
| 58 | |||
| 59 | print("------ Scenario 1 ------\n") |
||
| 60 | class ObserverA(observer): |
||
| 61 | def update(self, a_subject) -> None: |
||
| 62 | if a_subject.state == 0: |
||
| 63 | print("ObserverA: Reacted to the event") |
||
| 64 | |||
| 65 | s1 = subject([]) |
||
| 66 | # o1 = observer() |
||
| 67 | # s1.attach(o1) |
||
| 68 | |||
| 69 | # business logic |
||
| 70 | s1.state = 0 |
||
| 71 | s1.notify() |
||
| 72 | |||
| 73 | print("------ Scenario 2 ------\n") |
||
| 74 | # example 2 |
||
| 75 | class Businessubject(subject): |
||
| 76 | |||
| 77 | def some_business_logic(self) -> None: |
||
| 78 | """ |
||
| 79 | Usually, the subscription logic is only a fraction of what a Subject can |
||
| 80 | really do. Subjects commonly hold some important business logic, that |
||
| 81 | triggers a notification method whenever something important is about to |
||
| 82 | happen (or after it). |
||
| 83 | """ |
||
| 84 | print("\nSubject: I'm doing something important.") |
||
| 85 | from random import randrange |
||
| 86 | self._state = randrange(0, 10) |
||
| 87 | print(f"Subject: My state has just changed to: {self._state}") |
||
| 88 | self.notify() |
||
| 89 | |||
| 90 | class ObserverB(observer): |
||
| 91 | def update(self, a_subject) -> None: |
||
| 92 | if a_subject.state == 0 or a_subject.state >= 2: |
||
| 93 | print("ObserverB: Reacted to the event") |
||
| 94 | |||
| 95 | s2 = Businessubject([]) |
||
| 96 | assert id(s1) != id(s2) |
||
| 97 | assert id(s1._observers) != id(s2._observers) |
||
| 98 | o1, o2 = ObserverA(), ObserverB() |
||
| 99 | # s2.attach(o1) |
||
| 100 | # s2.attach(o2) |
||
| 101 | s2.add(o1, o2) |
||
| 102 | # business logic |
||
| 103 | print(s2._observers) |
||
| 104 | s2.some_business_logic() |
||
| 105 | s2.some_business_logic() |
||
| 106 | |||
| 107 | s2.detach(o1) |
||
| 108 | s2.some_business_logic() |
||
| 109 |