Header Ads

Header ADS

clean code 1






 Have you ever seen a code that makes you want to throw away your computer?😖 Well in the other hand you may see a code that if, even you don’t know the language or the concept, you get the idea behind!😍 That’s called clean code and in this article I will teach you how to write a one😀 .

The clean code may have a few principals: readable /Reusable/follows best practices and fun!

In a nutshell you should treat your code as a story.

1-Names:

Names should be meaningful,

const obj = new MyObject()

 

obj.create();

 

if (test){

    console.log(test)

}

This is a bad code. You can’t understand the concept form the first sight! But:

const admin = new Admin()

 

if(admin.isFree)

   console.log(admin.name)

This is a good one. You can have an idea about the methods and proprieties of Admin class.

In general: use nouns/verbs with adjectives.  

 snake_case: like is_valid/send_request

camelCase: like isValid/sendRequest

Just make it clear and meaningful

2-comments:

Don’t repeat yourself.

//creating an admin

const admin = new admin()

//update a user

db.createUser(newUser)

there’s no need to tell when creating an object.

The second comment is saying update but the function and the variable says it’s creation of a new one! Be careful it’s not the same. Remember that your work will read by other developers the may mismatch the function.

//works only in web environment

localStorage.setItem('user','name')

//it requires a @ and a dot

const emailRegex = /\S+@\S+\.\S+/;

//to do : fix the bug in ...

Now some good comments. The first one reminder of a crucial conditions or a warning.

The second simplify the regular expression written. Very useful if another developer see it.

 Or as last example a to do note

Formatting:

It’s how your code looks.

When working with classes or models it’s better to separate each one in a file. When working with variables or function it’s better to regroup them by usage and roles.







See this code. Do you understand something?

Now see it again:



 

Some spacing and formatting have changed a lot!

Keep related concept close to each other .

If you are using vscode I highly recommend to install formatter packages like prettier.

When having a long line it’s better to divide it .

if(type.value==="invoice")

    doc =new Invoice(tofrom.value,

        details.value,

        amount.valueAsNumber

        );

else 

    doc =new Payment(tofrom.value,

        details.value,

        amount.valueAsNumber

        );

    

This is the previous code after some modification.

Now as an exercise try to look into you previous code and clean it. With those small step you will learn to know the clean code from the messy one.😉

Don’t worry I didn’t finish yet. See you in the next article.😍

No comments

Theme images by enot-poloskun. Powered by Blogger.