Shubham Ankit

Shubham Ankit

1567217986

How to Write Clean Code: an Overview of JavaScript Best Practices and Coding Conventions

How to Write Clean Code: an Overview of JavaScript Best Practices and Coding … Coding conventions are style guidelines for programming.

Introduction

Coding conventions are style guidelines for programming. They typically cover:

  • Naming and declaration rules for variables and functions.
  • Rules for the use of white space, indentation, and comments.
  • Programming practices and principles

In this article, I’m going to cover most important JavaScript code conventions. If you stick to the rules stated in this article, people will perceive your work differently. Your team and your boss will appreciate you for writing clean code, but most importantly, you will be thankful to yourself. Everyone appreciates clean code.

Coding conventions **secure quality, improve code readability and make code maintenance easier. **They can be documented rules for teams to follow, or just be your individual coding practice.

“Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.” - Robert C. Martin
Let’s get started!

Just a note

Along with writing this article, I have also created a YouTube Video.

In the video, I go into much greater detail of each specific coding convention and I throw in a few extra examples to verify each specific rule.

Here’s a link to the full video: https://www.youtube.com/watch?v=RMN_bkZ1KM0.

Coding Conventions

To start, let’s begin by asking what isn’t clean code? Our examples will be based around JavaScript.

So what are some of the things you can start doing to make it easier for you and your team? Let’s start with simple naming conventions.

Always use the same coding conventions for all your JavaScript projects.

Magic numbers

Assigning a number that has no clear meaning. If you look at this code for a first time, you will have no idea what the number 86400 should represent.

for(let i = 0; i < 86400; i += 1) {
  // ...
}

It’s better to replace it with a named constant:

const SECOND_IN_A_DAY = 86400;

for(let i = 0; i < SECOND_IN_A_DAY; i += 1) {
  // ...
}

Later in article you’ll also learn why we used upper case snake case for this example.

Deep nesting

If your code contains many nested loops or conditional statements, then this should probably be extracted into a separate function.

const exampleArray = [ [ [ 'value' ] ] ];

exampleArray.forEach((arr1) => {
  arr1.forEach((arr2) => {
    arr2.forEach((el) => {
      console.log(el)
    })
  })
})

// output: 'value'

For this particular example, we can create a function that will loop through all arrays and return a final value:

const exampleArray = [ [ [ 'value' ] ] ];

const retrieveFinalValue = (element) => {
  if(Array.isArray(element)) {
    return fetchValue(element[0]);
  }

  return element;
}

// output: 'value'

Stop writing comments

Although subjective, the use of comments in your code can be helpful, but could be a sign your code is failing to be self explanatory.

“While comments are neither inherently good or bad, they are frequently used as a crutch. You should always write your code as if comments didn’t exist. This forces you to write your code in the simplest, plainest, most self-documenting way you can humanly come up with.” - Jeff Atwood
Code must speak for itself!

Avoid large functions

A function or even a class that is large in size suggests that it’s doing more than it should. This example may seem simple, but it proves a point. This function does a lot more than it should be doing.

const addMultiplySubtract = (a, b, c) => {
  const addition = a + b + c;
  const multiplication = a * b * c;
  const subtraction = a - b - c;

  return `${addition} ${multiplication} ${subtraction}`;
}

It is better to create different functions to separate the logic:

const add = (a, b, c) => a + b + c;
const multiply = (a, b, c) => a * b * c;
const subtract = (a, b, c) => a - b - c;

Code repetition

If you have to copy and paste a block of code, it’s a sign that that the repeated block may need to be extracted into its own function.

Great example of this is our deep nesting example:

const exampleArray = [ [ [ 'value' ] ] ];

exampleArray.forEach((arr1) => {
  arr1.forEach((arr2) => {
    arr2.forEach((el) => {
      console.log(el)
    })
  })
})

In here, we have a lot of repeated code. It’s much better to extract it to a separate it into a different function and handle logic differently, with less repetition:

const exampleArray = [ [ [ 'value' ] ] ];

const retrieveFinalValue = (element) => {
  if(Array.isArray(element)) {
    return fetchValue(element[0]);
  }

  return element;
}

Another great example of code repetition would be retrieving data from parameters:

const getUserCredentials = (user) => {
  const name = user.name;
  const surname = user.surname;
  const password = user.password;
}

Using ES6 object destructuring we can simply do the following:

const getUserCredentials = (user) => {
  const { name, surname, password } = user;
}

Variable Names

Camel case is used for almost everything in JavaScript. Camel case is a naming standard we use for identifier names (variables and functions).

It states that a name needs to begin with a lower-case letter and then, every first letter of the next word is uppercased. Here are some examples:

thisIsARandomCamelCaseName, camelCase, exampleFunctionName, you get the point.

Use meaningful names

getUserData and getUserInfo are vague. What data or info are you getting?

It is important that our functions, methods and variable names express their exact meaning.

getUserPost is much better, we can understand exactly what we’re getting.

When in doubt, favor descriptive over concise

Be as concise as possible; however, if you are having difficulty finding a two or three word description for your name, it is better to stay on the side of being descriptive.

findUserByNameOrEmail and setUserLoggedInTrue is better than findUser.

When there is a shorter version, use it

While getUserFromDatabase is very descriptive, there is a shorter version that means the same thing. The keq question you should ask yourself is “does fromDatabase add any meaning t0 your program?”

The answer is that it most likely doesn’t, we can assume that we’re fetching the user from the database.

Use consistent verbs per concept

Functions will usually create, read, update or delete something. You could even be a bit more descriptive and say they: create, get, set, add, remove, reset, and delete things.

A function should be a verb or a verb phrase, and must communicate its intent.

We need to be consistent with our verbs, for fetching we can always use get, rather than get, retrieve, return and ten thousand different names:

getQuestions getUserPosts getUsers rather than:

getQuestions returnUsers retrieveUsers.

Obviously, there are different variations of these words, but whichever you choose, stay consistent. For example, when you remove something use “delete” or “remove” (not both) throughout your entire program.

Make booleans that read well in if-then statements

A good test for boolean variable names is to put the name in an if-then statement and read it outloud. If it reads like a natural sentence, you’re in a good shape.

For example, if we’re checking the characteristics of a car, which naming would you find more convenient?

sedan, sold, green, airbag, or;

isSedan, isSold, isGreen, hasAirbag.

And now if we’re checking the properties, we can do something like this:

car.isSedan, car.isSold, car.hasAirbag (much better than car.airbags) and we immediately know that we’re dealing with boolean values.

Those sound more natural and make the program easier to decipher.

Use nouns for classNames

Classes don’t take things, they are things.

More specifically, they are a blueprint for something. Instantiating a class is what makes something.

class Car = {...} and not class MakeCar {...}.

If you were to make a new car you wouldn’t say “make a new MakeCar”, you would say: “make a new Car”.

Use PascalCase for classNames.

Pascal case makes it easier to see which items are classes and which items aren’t.

class Task {...} rather than class task {...}.

Capitalize constant values

Remember that we specified the seconds in a day like SECOND_IN_A_DAY = 86400?

A constant value is something that won’t change. This convention has roots in C and is not always followed in JavaScript.

Keep in mind const and the term constant are not the same. The const declaration simply means the value can’t me mutated through reassignment. Whereas a true constant value is a primitive value that won’t be changed later.

Also, you may consider narrowing the definition to values that are not only primitive but also inherently fixed: such as hours in a day, the value of PI, or the names of days in a week.

For example:

const HOURS_IN_DAY = 24; and const USER_AGE = 30; are primitive values that aren’t going to change, variables that are not set in stone should not be capitalized: const USER = foundUser; const TODAY = new Date ();.

Avoid one-letter variable names

A shortened names causes more hassle than the keystrokes you save in the long run.

Names should be concise and descriptive. A variable initialized in the global scope may end up being use one hundred lines later. It becomes easy to forget what it was if it is only a single letter.

const dueDate = new Date() is much better than const d = new Date();

const query = () => { ... }; is much better than const q = () => { ... };

If you use a single-letter variable names, limit them to small function or as index variables in loops (this is okay):

for(let i = 0; i < 10>; i ++) { // ... }

Remember these conventions for your own future sanity.

Summary

To summarise, there are huge benefits to following these rules in the long run. Others may pick up the code you’ve written in a few days, months or even years, scan from top to bottom, and either sigh of relief or frustration. Which one would you prefer?

Clean code makes it easier to start and continue coding it is better for the individual as well as a team and it is much easier to read.

Characteristics of a Clean code:

  1. “It should be elegant — Clean code should be *pleasing *to read. Reading it should make you smile the way a well-crafted music box or well-designed car would.”
  2. “Clean code is focused —Each function, each class, each module exposes a single-minded attitude that remains entirely undistracted, and unpolluted, by the surrounding details.”
  3. “Clean code is taken care of. Someone has taken the time to keep it simple and orderly. They have paid appropriate attention to details. They have cared.”

#javascript #web-development

What is GEEK

Buddha Community

How to Write Clean Code: an Overview of JavaScript Best Practices and Coding Conventions
Osiki  Douglas

Osiki Douglas

1624789560

Best Practices to Write Clean Python Code

Python is one of the most loved programming languages today. Shockingly, Python has overtaken Java in the list of top programming languages and is now the most studied language! It is the second most used language after JavaScript and is slowly beating the competition to be on the top. It is used extensively across various domains like web development through popular frameworks like Django and Flask, web scraping, automation, system administration, DevOps, testing, network programming, data analysis, data science, machine learning, and artificial intelligence. In fact, the first language which comes to someone’s mind when talking about data-related technologies is Python!

Along with being a heavily used language by beginners due to its ease of learning, it has huge community support and extensive documentation. But a lot of people when switching from other languages like Java, C, C++, JavaScript etcetera, find it a little difficult to follow along with the best practices that should be adopted to write clean code in Python. Clean code is easier to read and understand, debug, and elegant. So today we will be discussing all of them in detail, therefore you will get a better idea of them. So let’s get started!

#gblog #python #best practices to write clean python code #clean python code #best

Seamus  Quitzon

Seamus Quitzon

1600061880

How to write clean code ? follow these best practices for writing clean code

Hey programmers , this article is not about some java related feature or concept but more than that . Basically I’m going to explain what all mistakes a java developer does while writing the code and hence how you can minimize it and you don’t have to refactor your code .So this article is about BEST PRACTICES a developer should always follow .

1. What’s there in the name :

A developer should always try to give a meaningful name to the variables, methods and classes . It becomes too easy to understand what the method or class or variable is about when some one reads your code while reviewing it or debugging it. Giving name like a ,b,c to variable do not intent any meaning and becomes less relevant while debugging the code .

  1. Always start the name of a class with upper case .Eg.
public class Employee {

}

here **Employee **is class name and other developers can easily understand that this class deals with employee related stuff.

2. Always start a variable name with lower case .Eg.

private int salary;

here **salary **tells about salary of employee .

3.Always start method name with lower case and do not include And and Or words in method name .Eg.

public int calculateSalary(int noOfDaysWorked , int baseSalary)

4. Write constants in upper case and separate them with under score .Eg.

public final int RETIREMENT_AGE = 58;

Note : do not use special symbols while writing variables ,methods , constants or classes names .

#programming #best-practices #code-review #java #coding

Gordon  Taylor

Gordon Taylor

1624692360

50 JavaScript Best Practice Rules to Write Better Code

JavaScript is powerful and flexible which allows you to code any way you like and try some very unusual things which can lead to a bug in your code. Here are 50 things I learned about coding in JavaScript you should know about.

Always  “use strict” On

Use Function expressions instead of Function Declarations

Stop using “var”!

Use “const” and immutability as much as possible

Prefer Pure Functions

Prefer Class over Constructor Functions

Use “destructuring”

Only work with data you need

Always use “===”

Avoid Global Variables

Wrap loose declarations in blocks

Organize your declarations

Don’t initialize things with “undefined”

Always initialize your declarations

Lint your code and have a consistent style

Use TypeScript

Functions and methods should do one thing only

Don’t be lazy when naming things

Avoid unnecessary declarations

Use default values when possible

Always have a default case for switch statements

Never use “eval”

Avoid the “new” keyword

Add meaningful comments for nonobvious things

Keep ternaries simple

Simplify with optional chaining

Prefer promises over callbacks

For loops > .forEach sometimes

“for…in” and “for…of”

Optimize for loops?

Always “try…catch” JSON methods

Prefer template strings

Avoid nesting or chaining loops

Avoid Weird Unreadable hacks

Prefer the  “rest” operator over  “arguments”

#coding #javascript #best-practices

Giles  Goodwin

Giles Goodwin

1603857900

4 Ways You Can Get Rid of Dirty Side Effects for Cleaner Code in JavaScript

According to an analysis, a developer creates 70 bugs per 1000 lines of code on average. As a result, he spends 75% of his time on debugging. So sad!

Bugs are born in many ways. Creating side effects is one of them.

Some people say side effects are evil, some say they’re not.

I’m in the first group. Side effects should be considered evil. And we should aim for side effects free code.

Here are 4ways you can use to achieve the goal.

1. use strict;

Just add use strict; to the beginning of your files. This special string will turn your code validation on and prevent you from using variables without declaring them first.

#functional-programming #javascript-tips #clean-code #coding #javascript-development #javascript

Code Trashing Symptom

There are a set of skills and qualities which make the ideal software

developer we are all searching to be or searching for to employ. However, right now I am going to emphasize the importance of a quality that is mostly found in senior developers.

As a beginner, I remember the enthusiasm when I implemented my first app. It was in VisualBasic v6.0 with very basic UI and logic. From there on,

it was very hard to leave the keyboard without writing code daily. At

first, it was VB, then some HTML, JavaScript (when it was very buggy),

Java, and sometime later I became a true working developer/team-leader

for many years.

Reliving those days when I was an enthusiast developer, I remember the powerful feeling that kept me on my path. I was (and still) addicted to code. But it is not code I was after. It is the vast feeling of creating something your own. Creating something from within. This strong feeling of a new creation is addictive.

The problem with addiction is that you don’t recognize the limits of

yourself and your creations. Consequently, you are not guided by your

consciousness.

As a leader of development teams in different projects, I came across a

variety of situations with different developers. But this same question I kept hearing from time to time, “This is a great piece of code, do you really want me to remove it?”, and it is really a great piece of code with the ultimate design.

But what you shouldn’t forget that you and your team are here to accomplish something meaningful for your clients and users! Thus writing a greatly designed code with low correlation to requirements isn’t going to change anything.

When I moved to my current team and project, I found out that the project’s code was written beautifully and well designed. But it was insignificant to our client’s future requirements.

One of the best decisions I made was to gradually re-implement (remove old code and write a new one without reference nor copy-pasting any parts). The reason being the already written code was a big hurdle to bend to any new requirements we received

Sometimes it’ll be hard to ask for, especially when you’re asking the original author of the code. But always remind him of these facts: your main focus is your clients; if you miss your code, Github will always remember it for you.

Acknowledging your addiction to code is your first step to overcoming your unconscious desire to create worthless stuff that no one will use (and believe me, it hurts more to find out that your code is useless than

removing a code you’ve written).

Final Thoughts

From my personal experience, when you implement something hard to solve the first time, most of your energy and thoughts are invested in solving the problem and not in the most relevant design for the given requirements.

Rewriting the same code a second time gives you a second chance to spend your time (almost solely) in design (since the problem is already

solved).

The best design is a design made for the current (known) requirements and not future mystic stuff that we just came up with.

**Remember: **Refactor! Don’t predict!

#clean-code #best-practices #programming #development #refactoring #coding #coding-skills #coding-life