shape
shape
shape
shape
shape
shape

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!

Beautiful JavaScript - How to code for beauty? - Part 1
This is the first post in the series, so I have some pre-shared thoughts about my own priorities in coding.
The three main issues I often pay attention to are performance, maintainable and coding speed.

My order of priority is maintainable > performance > coding speed. Of course, this is a normal order of precedence, and by no means means choosing one of the three.

That order means that I will prioritize the code clean and easy to understand, can complete the code 5, 10 minutes slower, can perform a little slower, declare a little more variables, ... of course it's just a little bit, and often that little bit we don't even realize, because performance in most cases for me is the story of the computer hardware, we just need not violate some big principles performance is ok.

And the above order can also change according to each stage in the product development life cycle, for example, when a deadline is reached, coding speed will then be prioritized above all, of course we still have to ensure performance and maintainable acceptable.

Sharing this in advance so that you guys understand that most of my experiences and habits in this series are maintainable, and I think that's the most important thing when you code Front-end.
Let's start, in this first post, I will share 4 habits when writing my code.

1. Don't use else

I realize that in almost all cases we don't need to use the else statement, and in my code I almost never use else.

When I used else, it meant that I was lazy to think to write beautiful code.

For example, here I have a function to format data, with 2 input parameters as value and format:

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?

Imagine you have a form data on the front-end and need to validate it before sending it to the server, how will we handle it?

I have a habit of using try-catch in situations like this, it makes your code very easy to understand.
A simple example with a form with 2 fields name and age:
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.