Beautiful JavaScript - How to code for beauty? - Part 1
This series contains little experiences as well as habits when writing my code.
Writing to save is the main thing, but of course I really hope to be able to help someone :>
I will use JavaScript for the examples, but I think you can apply to other languages as well
Let's go!
1. Don't use else
const formatData = (value, format) => { if (format === "number") { return Number(value) } else if (format === "datetime") { return new Date(value) } else if (format === "boolean") { return !!value } else { return null }}
formatData("111", "number") // 111
Do you guys feel terrible eye pain when looking at this code like me? Let me fix it.
const formatData = (value, format) => {
if (format === "number") return Number(value)
if (format === "datetime") return new Date(value)
if (format === "boolean") return !!value
return null
}
formatData("111", "number") // 111
Much better!!!
Honestly, I prefer writing code like this to using switch cases, in case there aren't too many cases, of course.
2. How to validate data properly?
const send = (data) => { try { if (!data) throw new Error("Invalid data") if (!data.name || !data.name.trim()) throw new Error("Name is empty") if (!data.age || data.age < 18) throw new Error("Age is invalid") // some logic to send data to server } catch(err) { // do something with err.message // alert error for example }}
Do you feel okay? Some of you will want us to catch all the errors of the fields in the data, so I will add a little logic like this:
const send = (data) => {
try {
const errors = []
if (!data) throw new Error("Invalid data")
if (!data.name || !data.name.trim()) {
errors.push("Name is empty")
}
if (!data.age || data.age < 18) {
errors.push("Age is invalid")
}
if (!!errors.length) throw new Error(errors.join(", "))
// some logic to send data to server
} catch(err) {
// do something with err.message
// alert error for example
}
}
It's better then.
In fact, I rarely manually validate forms for forms with many complex fields. At that time, I recommend that you use a library to help you validate the form as well as handle some other more complex conditions.
For those of you who code React, I recommend formik and yup, the perfect couple :D
3. Keep the function simple
This principle you can find in any book or article about clean code, it is an important principle.
Try to keep a function that does only one task, and that task will be evident in the function name, nothing more, nothing less.
For example, the code in the other part 2, in fact, I will create a function to validate the data, and the send function is as simple as its name, it only sends data to the server.
const validateData = (data) => {
try {
const errors = []
if (!data) throw new Error("Invalid data")
if (!data.name || !data.name.trim()) {
errors.push("Name is empty")
}
if (!data.age || data.age < 18) {
errors.push("Age is invalid")
}
if (!!errors.length) throw new Error(errors.join(", "))
return true
} catch(err) {
// do something with err.message
// alert error for example
return false
}
}
const send = (data) => {
const passed = validateData(data)
if (!passed) return
// some logic to send data to server
}
You can see yourself for the validate function to return a boolean value to show if the data in the form is valid. The send function will take this value to check whether to send data to the server or not.
Remember, each function does a simple job, and is represented by its name. This is easy said, but sometimes very difficult to do
4. Don't try to write short code
I don't know why so many of you try to write code as short as possible, taking as few lines as possible.
At my company, React coders often joke that any component longer than 300 lines is garbage 😂😂😂
I really think garbage or not is due to the way the code is written and its flow, has nothing to do with the number of lines of code in a file or a component.
I'm perfectly fine with a 500-700 line component where the code is easy to understand and the logic flow is clear.
But it must also be said that packing too much logic in one file will make it very difficult for you to keep it understandable, and both confusing and long can also be called garbage 🤣🤣
In addition, I often have the habit of separating lines, each block of code is usually a small problem that the function needs to handle, as in the example in part 3, after calling the validateData function, I have a 1-line gap and then continue to write the logic. send.
This may sound small, but if it's a habit, your code will look nice and clean.
Don't forget that clean code must first and foremost be easy to see and read.
The above are 4 habits I often use when writing code, hopefully it can be of some help to you, especially those who are new to work or are practicing, because I really haven't worked for too long. :>
If you find this article useful, please leave a comment, I will be very grateful.
See you again in the next term.
Post a Comment