single responsibility functions
image aythor: https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSR5p42RUa9veMuZNWG-OvFyrx6No0qB3NZVg&usqp=CAU

single responsibility functions

How to make your function only have one responsibility?

As the name say it this principle talks about make functions with only one responsibility.

pros

  • more readable code
  • more robust
  • more maintainable
  • smaller functions

I'm going to explain with a practical example, imagine that you have the following function:

function getData(baseUrl, route) {
  fetch(`${baseUrl}${route}`)
    .then(response => response.json())
    .then(data => console.log(data));  
}

nothing weird with the above function, just a normal function, is a function that works with two arguments (baseUrl, route) and a simple fetch with the arguments, handle the response and that's it, looks like a single responsibility function but the true is not, the function above do 3 things, give the route, give the base url and fetch the data.

Let's make single responsibility for each responsibility

  1. first step is return an arrow function to handle the route appart the baseUrl, that allow us have apart the task to give the baseUrl and the task to give route
function getData(baseUrl) {

  return (route) => {

   fetch(`${baseUrl}${route}`)
    .then(response => response.json())
    .then(data => console.log(data));
 } 
 
}

you can use the above function like this:

const getExpecificData = getData("https://example.com")

const getUsersFromExpecificData = getExpecificData("/users")

You can see it? yes, it is completely beautiful

let's keep going

2. apply the above steps

function getData(baseUrl) {

  return (route) => {


  return (callback) => {

    fetch(`${baseUrl}${route}`)
    .then(response => response.json())
    .then(data => callback(data));

  }   

 } 
 
}


you can use the function like this:

const getExpecificData = getData("https://example.com")


const getUsersFromExpecificData = getExpecificData("/users")

const getUserNamesFromExpecificData = getUsersFromExpecificData(
     user => user.name  
  )
  


now we can handle the data of any fetch with any baseURL with any route.

I hope that you enjoy this post, all the best for you

要查看或添加评论,请登录

社区洞察

其他会员也浏览了