-
Notifications
You must be signed in to change notification settings - Fork 0
/
04_dip.py
64 lines (44 loc) · 1.58 KB
/
04_dip.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
58
59
60
61
62
63
64
# QUESTION: How does this violate dependency inversion principle?
class JSONReader():
def read(self, path):
pass
class JSONWriter():
def write(self, path, data):
pass
class App():
def __init__(self):
self.reader: JSONReader = JSONReader()
self.writer: JSONWriter = JSONWriter()
def load(self, path):
json = self.reader.read(path)
return json
def save(self, path, data):
self.writer.write(path, data)
## Notes ##
# Application currently depends on the implementation of JSON Reader and JSON Writer
# Suggested Code
from abc import ABCMeta, abstractmethod
class Reader(metaclass=ABCMeta):
@abstractmethod
def read(self, read_input) -> dict:
raise NotImplementedError()
class Writer(metaclass=ABCMeta):
@abstractmethod
def write(self, write_input, data) -> None:
raise NotImplementedError
class JSONReader(Reader):
def read(self, path):
pass
class JSONWriter(Writer):
def write(self, path, data):
pass
class App():
def __init__(self):
self.reader: Reader = JSONReader() # Depends on an abstraction not an implementation
self.writer: Writer = JSONWriter() # In the future, if we wanted to change the way we read and write data,
# we could easily swap our JSONReader and JSONWriter
def load(self, path):
json = self.reader.read(path)
return json
def save(self, path, data):
self.writer.write(path, data)