Skip to main content

Single Responsibility Principle

A class should be responsible for only one thing. If a class is responsible for several tasks, its subsystems, which implement these tasks, are related to each other. Changes in one such subsystem lead to changes in another.

Below is an example that does not conform to the single responsibility principle:

class TodoList {
constructor() {
this.items = []
}

addItem(text) {
this.items.push(text)
}

removeItem(index) {
this.items = items.splice(index, 1)
}

toString() {
return this.items.toString()
}

save(filename) {
fs.writeFileSync(filename, this.toString())
}

load(filename) { // Some implementation }
}

Try to refactor the code before seeing a solution

Example Solution
class TodoList {
constructor() {
this.items = [];
}
addItem(text) {
this.items.push(text);
}
removeItem(index) {
this.items = items.splice(index, 1);
}
toString() {
return this.items.toString();
}
}

class TodoDBManager {
saveToFile(data, filename) {
fs.writeFileSync(filename, data.toString());
}
loadFromFile(filename) {
// Some implementation
}
}