How single responsibility of a function helps to write better code

Let's consider this example code,

app.post('/user', (req, res) => {
  const userData = req.body

  if (!userData.name || !userData.email) {
    return res.status(400).json({ error: 'Name and email are required' })
  }

  User.create(userData, (err, newUser) => {
    if (err) {
      return res.status(500).json({ error: 'Failed to create a new user' })
    }
    return res.status(201).json(newUser)
  })
})

It does two things inside a single handler,

  • validates the input data
  • creates a new user

Let's refactor this code to follow the single responsibility principle. Separate the validation of user data and saving the user as separate functions,

function validateUserData(userData) {
  if (!userData.name || !userData.email) {
    throw new Error('Name and email are required')
  }
}

function saveUserToDatabase(userData) {
  return new Promise((resolve, reject) => {
    User.create(userData, (err, newUser) => {
      if (err) {
        reject(new Error('Failed to create a new user'))
      } else {
        resolve(newUser)
      }
    })
  })
}

Now, keep the route handler as simple as possible,

app.post('/user', (req, res) => {
  const userData = req.body

  try {
    validateUserData(userData)
  } catch (error) {
    return res.status(400).json({ error: error.message })
  }

  saveUserToDatabase(userData)
    .then((newUser) => res.status(201).json(newUser))
    .catch((error) => res.status(500).json({ error: error.message }))
})

Hope this article helps you to learn how single responsibility principle helps you to write self explanatory code 🚀

Beginners to ProNode Js

API Design Best Practices

This visual eBook covers essential best practices for designing robust APIs using REST principles.

This book is ideal for beginners and backend developers seeking to enhance their API design skills. However, it is not suited for those seeking an in-depth exploration of API design. This book is a quick read under 40 slides like scrolling through your instagram feed.

API Design Best Practices