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 🚀

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay