-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathsingle_responsibility.py
57 lines (42 loc) · 1.2 KB
/
single_responsibility.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
Single Responsibility Principle
- A class only have one reason to change
- Separation of concerns:
- different classes handling different, independent
tasks/problems
"""
class Journal:
def __init__(self):
self.entries = []
self.count = 0
def add_entry(self, text):
self.count += 1
self.entries.append(f'{self.count}: {text}')
def remove_entry(self, pos):
del self.entries[pos]
def __str__(self):
return '\n'.join(self.entries)
# methods below give class responsibility of persistence, bad idea!
def save(self, filename):
file = open(filename, 'w')
file.write(str(self))
file.close()
def load(self, filename):
pass
def load_from_web(self, url):
pass
J = Journal()
J.add_entry('I cried today.')
J.add_entry('I ate a bug.')
print(f'Journal entries:\n{J}')
# instead, create another class to handle that responsibility
class PersistenceManager:
@staticmethod
def save_to_file(self, journal, filename):
file = open(filename, 'w')
file.write(str(self))
file.close()
def load(self, filename):
pass
def load_from_web(self, url):
pass