Using Open/Closed Concept in hooks
SOLID is a design pattern commonly used in various programs. Some developers think that the concepts from SOLID can only be applied in OO (object-oriented) programs.
So, this article will show that we can apply SOLID concepts in our React project, specifically SOLID using hooks.
The original concept of open/closed is:
“software entities (classes, modules, functions, etc) should be open for extension, but closed for modification”.
I took the time to understand the real meaning.
领英推荐
So put it in words for React developers, this meaning: Write hooks/components which you never need to touch again, only re-use them in other hooks/components.
Refer to the code below and think about why the open/closed concept is not followed.
const useUser = ({ userType }) => {
const [user, setUser] = useState()
useEffect(() => {
const userInfo = getUser()
setUser(userInfo)
}, [])
const updateEmail = (newEmail) => {
if (user && userType === 'admin') {
updateUser({ ...user, email: newEmail })
} else {
console.error('Cannot update email')
}
}
return { user, updateEmail }
}
This code won’t get you fired, but we can always improve, right? So, do you understand why it does not follow the concept ??
Imagine you need to insert a new type of user, you would probably add a new “if” statement with the user’s types and their specificities. By doing this, you are modifying the code instead of extending it. So, now that you know about this concept, follow the code that you will create.
const useUser = () => {
const [user, setUser] = useState()
useEffect(() => {
const userInfo = getUser()
setUser(userInfo)
}, [])
return { user }
}
const useAdmin = () => {
const { user } = useUser()
const updateEmail = (newEmail) => {
if (user) {
updateUser({ ...user, email: newEmail })
} else {
console.error('Cannot update email')
}
}
return { user, updateEmail }
}
Mobile Engineer | React Native Developer | React | TypeScript | JavaScript | Mobile Developer | Node
6 个月Great content Otávio Soares! Thanks for sharing