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
bindu singh

bindu singh

1647351133

Procedure To Become An Air Hostess/Cabin Crew

Minimum educational required – 10+2 passed in any stream from a recognized board.

The age limit is 18 to 25 years. It may differ from one airline to another!

 

Physical and Medical standards –

  • Females must be 157 cm in height and males must be 170 cm in height (for males). This parameter may vary from one airline toward the next.
  • The candidate's body weight should be proportional to his or her height.
  • Candidates with blemish-free skin will have an advantage.
  • Physical fitness is required of the candidate.
  • Eyesight requirements: a minimum of 6/9 vision is required. Many airlines allow applicants to fix their vision to 20/20!
  • There should be no history of mental disease in the candidate's past.
  • The candidate should not have a significant cardiovascular condition.

You can become an air hostess if you meet certain criteria, such as a minimum educational level, an age limit, language ability, and physical characteristics.

As can be seen from the preceding information, a 10+2 pass is the minimal educational need for becoming an air hostess in India. So, if you have a 10+2 certificate from a recognized board, you are qualified to apply for an interview for air hostess positions!

You can still apply for this job if you have a higher qualification (such as a Bachelor's or Master's Degree).

So That I may recommend, joining Special Personality development courses, a learning gallery that offers aviation industry courses by AEROFLY INTERNATIONAL AVIATION ACADEMY in CHANDIGARH. They provide extra sessions included in the course and conduct the entire course in 6 months covering all topics at an affordable pricing structure. They pay particular attention to each and every aspirant and prepare them according to airline criteria. So be a part of it and give your aspirations So be a part of it and give your aspirations wings.

Read More:   Safety and Emergency Procedures of Aviation || Operations of Travel and Hospitality Management || Intellectual Language and Interview Training || Premiere Coaching For Retail and Mass Communication |Introductory Cosmetology and Tress Styling  ||  Aircraft Ground Personnel Competent Course

For more information:

Visit us at:     https://aerofly.co.in

Phone         :     wa.me//+919988887551 

Address:     Aerofly International Aviation Academy, SCO 68, 4th Floor, Sector 17-D,                            Chandigarh, Pin 160017 

Email:     info@aerofly.co.in

 

#air hostess institute in Delhi, 

#air hostess institute in Chandigarh, 

#air hostess institute near me,

#best air hostess institute in India,
#air hostess institute,

#best air hostess institute in Delhi, 

#air hostess institute in India, 

#best air hostess institute in India,

#air hostess training institute fees, 

#top 10 air hostess training institute in India, 

#government air hostess training institute in India, 

#best air hostess training institute in the world,

#air hostess training institute fees, 

#cabin crew course fees, 

#cabin crew course duration and fees, 

#best cabin crew training institute in Delhi, 

#cabin crew courses after 12th,

#best cabin crew training institute in Delhi, 

#cabin crew training institute in Delhi, 

#cabin crew training institute in India,

#cabin crew training institute near me,

#best cabin crew training institute in India,

#best cabin crew training institute in Delhi, 

#best cabin crew training institute in the world, 

#government cabin crew training institute

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