single responsibility functions
Bernardo Aguayo Ortega
Senior Software Engineer @ Ubidots | React & Next.js Specialist | Building Scalable Web Applications with JavaScript, TypeScript, and Node.js
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
- 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