How single responsibility of a function helps to write better code

šŸ”„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days

Coding with AI: Learn to build a SaaS MVP in 10 days

Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.

  • šŸŽÆ Build real MVP: AI-powered SaaS from idea to launch
  • šŸ¤– Integrate ChatGPT, Claude, and other AI APIs efficiently
  • šŸ’° Implement AI features users will pay for
  • āš”ļø AI-assisted coding patterns to ship 10x faster
  • šŸš€ Launch your product in 10 days, not 10 months

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 šŸš€