| Conditions | 3 |
| Total Lines | 52 |
| Code Lines | 30 |
| 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 |
||
| 67 | def test_scenario(subject, observer): |
||
| 68 | # The client code. |
||
| 69 | |||
| 70 | print("------ Scenario 1 ------\n") |
||
| 71 | class ObserverA(observer): |
||
| 72 | def update(self, a_subject) -> None: |
||
| 73 | print("ObserverA: Reacted to the event") |
||
| 74 | |||
| 75 | s1 = subject([]) |
||
| 76 | # o1 = observer() |
||
| 77 | # s1.attach(o1) |
||
| 78 | |||
| 79 | # business logic |
||
| 80 | s1.state = 0 |
||
| 81 | s1.notify() |
||
| 82 | |||
| 83 | print("------ Scenario 2 ------\n") |
||
| 84 | # example 2 |
||
| 85 | class Businessubject(subject): |
||
| 86 | |||
| 87 | def some_business_logic(self) -> None: |
||
| 88 | """ |
||
| 89 | Usually, the subscription logic is only a fraction of what a Subject can |
||
| 90 | really do. Subjects commonly hold some important business logic, that |
||
| 91 | triggers a notification method whenever something important is about to |
||
| 92 | happen (or after it). |
||
| 93 | """ |
||
| 94 | print("\nSubject: I'm doing something important.") |
||
| 95 | from random import randrange |
||
| 96 | self._state = randrange(0, 10) |
||
| 97 | print(f"Subject: My state has just changed to: {self._state}") |
||
| 98 | self.notify() |
||
| 99 | |||
| 100 | class ObserverB(observer): |
||
| 101 | def update(self, a_subject) -> None: |
||
| 102 | if a_subject.state == 0 or a_subject.state >= 2: |
||
| 103 | print("ObserverB: Reacted to the event") |
||
| 104 | |||
| 105 | s2 = Businessubject([]) |
||
| 106 | assert id(s1) != id(s2) |
||
| 107 | assert id(s1._observers) != id(s2._observers) |
||
| 108 | o1, o2 = ObserverA(), ObserverB() |
||
| 109 | # s2.attach(o1) |
||
| 110 | # s2.attach(o2) |
||
| 111 | s2.add(o1, o2) |
||
| 112 | # business logic |
||
| 113 | print(s2._observers) |
||
| 114 | s2.some_business_logic() |
||
| 115 | s2.some_business_logic() |
||
| 116 | |||
| 117 | s2.detach(o1) |
||
| 118 | s2.some_business_logic() |
||
| 119 |