Single Responsibility Principle

In programming, it is said that a function should do one thing and do it well for various reasons(simplicity, maintainability, reusability, and testability.)

For example, in the function below, we have multiple responsibilities: adding the task to the list, converting the list to JSON, and writing the JSON to a file.

const fs = require("fs");

function addTaskAndSaveToFile(task, tasksList, filePath) {
  // Step 1: Add the task to the tasks list
  tasksList.push(task);

  // Step 2: Convert tasks list to JSON string
  const tasksJSON = JSON.stringify(tasksList);

  // Step 3: Write the JSON string to a file
  fs.writeFileSync(filePath, tasksJSON);
}

We can rewrite the function so that a function can be responsible for one thing:

const fs = require("fs");

function addTask(task, tasksList) {
  tasksList.push(task);
  return tasksList;
}

function convertListToJSON(tasksList) {
  return JSON.stringify(tasksList);
}

function saveToFile(data, filePath) {
  fs.writeFileSync(filePath, data);
}

In a startup, we can think of each individual like a function. They should usually do only one thing and do it well. If you are in charge of sales, you get customers no matter what. If you are in charge of the backend development, you build a reliable system no matter what. Obviously, team dynamics is much more nuanced than this and they should be encouraged to collaborate. However, single responsibility principle helps individuals to 1) hold themselves accountable and 2) leave no room for excuses.

The best thing I did as a manager at PayPal was to make every person in the company responsible for doing just one thing. Every employee’s one thing was unique, and everyone knew I would evaluate him only on that one thing.”
Zero to One - Peter Thiel



Date
March 27, 2023