clean code 2
For a function you should minimize the number of
parameter.
//bad
saveUser("test.com","tester");
//meduim
const user = {mail :"test.com" ,name:"tester"}
saveUser(user)
//good
const user = new user('test.com','tester')
user.saveUser()
Look to those examples. We don’t need to guess which parameter is the first and which type is which.
In case we have too parameters
it’s recommended to use an array or an object.
class User {
constructor(data){
this.name = data.name,
this.age = data.age,
this.email = data.email
}
}
const me = new User({name:"name",age:"age",email:"email"})
we can pass the data as an object so we can specify
the parameter name and order and less confusing.
Most important, function must be small and do one thing! Don’t hesitate to divide your logic into different functions and call functions inside others😉.
Your code
should be like a story💚.
DRY: Don’t Repeat Yourself.
You should stay DRY. If a
logic is repeating extract it inside a function.
In case of nested conditions, use Guards and fast
fail. Compare both statement in case you have 5 if check and each one is nested
inside another. The second one is a way better. It means that the code will
stop executing if the first condition wasn’t satisfied!
//bad
if(email.include("@") ){
//other conditions ...
}
//good
if(!email.include("@"))return ;
//other conditions ...
Now, when handling error it’s better to create a
clear errors💪! Well ,each language have its specific way to do that try just to
comment it with a message.
When working with classes:
Use getters and setters to manipulate private data. So that you don't risk to change data accidentally. Don't forget what we said about functions! Keep it as small as possible.
Don't forget to use generic classes when working with nearly similar classes. Inheritance is a key concept in OOP. Use it wisely.
Write extensible and reusable code. You will definitely scale up you project or reuse some part of it.
Well for sure there are more but I think those are the main concept to know.
Hope you liked it.😍
No comments