Created: 2023-03-02 08:40
Status: #concept
Subject: Programming
Tags: JavaScript JavaScript Objects Java Inheritance Polymorphism
SOLID Principles
Single Responsibility
A Class or JavaScript Modules should only have ONE responsibility.
- This doesn’t mean that an object can only do one thing, but it does mean that everything an object does should be part of one responsibility.
- Separate updating & writing to the DOM away from our Application Logic.
Otherwise, if an object is trying to have multiple responsibilities, changing one aspect might affect another.
Before:
function isGameOver() {
// game over logic goes here!
if (gameOver){
const gameOverDiv = document.createElement('div');
gameOverDiv.classList.add('game-over');
gameOverDiv.textContent = `${this.winner} won the game!`;
document.body.appendChild(gameOverDiv);
}
}
After:
function isGameOver() {
// game over logic goes here!
if (gameOver){
DOMStuff.gameOver(this.winner);
}
}
Open-Closed
Objects or entities should be open for extension, but closed for modification.
- Open for extension means that we should be able to add new features or components to the application without breaking existing code.
- Closed for modification means that we should not introduce breaking changes to existing functionality.
Liskov Substitution
All this is stating is that every subclass/derived class should be substitutable for their base/parent class.
- a subclass should override the parent class methods in a way that does not break functionality from a client’s point of view.
Interface Segregation
A client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they do not use.
Dependency Inversion
Entities must depend on abstractions not on concretions.
- It states that the high level module must not depend on the low level module, but they should depend on abstractions.