Dependency inversion
Lesson 26 of 28 in Coddy's Clean Code - Write better code using Python course.
"Depend upon abstractions, [not] concretions."
Let's show example which violates the principle,
class LocalStorage:
def save(self, key, value):
print("Saved, " + key + ":" + value)LocalStorage class saves key and value pair.
Now we have another main class which uses the LocalStorage,
class App:
def start(self, key, value):
storage = LocalStorage()
storage.save(key, value)LocalStorage is a concrete implementation and App depends on it!
The better way would be to create interface (abstract class),
from abc import ABC, abstractmethod
class Storage(ABC):
@abstractmethod
def save(self):
passAnd then use instance of the interface instead of the concrete implementation.
Challenge
EasyYou are given code which is almost done, add the abstract class Storage.
Notice that after the implementation it's easy to change to other concrete class for example CloudStorage...
Try it yourself
from abc import ABC, abstractmethod
# your code here
class LocalStorage(Storage):
def save(self, key, value):
print("Saved, " + key + ":" + value)
class App:
def __init__(self, storage):
self.storage = storage
def start(self, key, value):
storage.save(key, value)
if __name__ == "__main__":
storage = LocalStorage()
app = App(storage)
key = input()
value = input()
app.start(key, value)