Programming principles and design · Lesson 35 of 60 · Concept lesson · Optional
SOLID principles
SOLID is five habits for object-oriented code: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.
Each one is a way of keeping parts small, replaceable and loosely connected.
They are guidelines, not laws, so use them when they make code simpler.
Picture it
Code example
class ConsoleSender {
send(text) {
console.log(text);
}
}
class Notifier {
constructor(sender) {
this.sender = sender;
}
notify(text) {
this.sender.send(text);
}
}
new Notifier(new ConsoleSender()).notify("Hello");Output: Hello
Notifier depends on anything that has a send method, so ConsoleSender could be swapped for an email sender without changing Notifier. That is dependency inversion.
class ConsoleSender:
def send(self, text):
print(text)
class Notifier:
def __init__(self, sender):
self.sender = sender
def notify(self, text):
self.sender.send(text)
Notifier(ConsoleSender()).notify("Hello")Output: Hello
Notifier depends on anything that has a send method, so ConsoleSender could be swapped for an email sender without changing Notifier. That is dependency inversion.
Check yourself
Pick an answer for each question. You can retry as many times as you like.
Loading the questions…