DEV Community

Paramanantham Harrison
Paramanantham Harrison

Posted on • Originally published at learnwithparam.com

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)
  })
})
Enter fullscreen mode Exit fullscreen mode

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)
      }
    })
  })
}
Enter fullscreen mode Exit fullscreen mode

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 }))
})
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)