GithubHelp home page GithubHelp logo

js-code-smells's Introduction

Javascript Code Smells

Introduction

In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problem. According to Fowler, "a code smell is a surface indication that usually corresponds to a deeper problem in the system" - Code Smell - Wikipedia

Bottom line, we need to refactor code with smells to make it more maintainable and reduce the number of bugs it introduces.

Table of Contents

  1. Purposeless conditions
  2. Multiple return statements
  3. This or That
  4. Equality
  5. Broken Promises

Purposeless conditions

Synopsis

Purposeless conditions introduce unwanted complexity to the code. It also increases the vertical length of the function subtracting the readablity.

Avoid

  /* Example # 1 */
  function isNumber(test){
    if(typeof test === 'number')
      return true;
    else
      return false;
  }

  /* Example # 2 */
  function isNotBoolean(test){
    var retVal = false; //or any other initialization
    if(typeof test === 'boolean'){
      retVal = false;
    }
    else{
      retVal = true;
    }
    return retVal;
  }

Score

  /* Example # 1*/
  function isNumber(test){
    return typeof test === 'number';
  }
  
  /* Example #2 */
  function isNotBoolean(test){
    return typeof test !== 'boolean';
  }

Multiple return statements

Synopsis

There should generally be a single returning path from a function. Multiple return statements make it difficult to understand the flow of the function.

Avoid

  /* Example */
  function stringAdd(numString){
    var val = parseInt(numString);
    if(numString === NaN){
      return 0;
    }
    else{
      return val;
    }
  }

Score

  /* Example */
  function stringAdd(numString){
    return Number(numString) || 0;
  }

This or That

Synopsis

Assigning this to a variable is a general practive to maintain context in a function. This works but stinks and makes the code less recognizeable. Using constructs bind, call and apply to set context while calling a function is a more cleaner approach. Functions like forEach have a hidden parameter to set execution context.

Avoid

  /* Example 1*/
  function haircut(persons){
    var that = this;
    
    persons.forEach(function(person){
      that.cut(person);
    });
  }

Score

  /* Example 1*/
  function haircut(persons){
    persons.forEach(function(person){
      this.cut(person);
    }.bind(this));
  }
  
  /* Example 1 Alternate*/
  function haircut(persons){
    persons.forEach(function(person){
      this.cut(person);
    }, this); //hidden param to set context in `forEach`
  }

Equality

Synopsis

Javascript has two options when it comes to comparing values the double equals == and the triple equals === operators. The difference between the two is that triple equals does type checking as well as value checking, so 1 === '1' would be false where as 1 == '1' would be true. In order to avoid nasty surprises we should try to use the === majority of the time since it helps us assert the types as well.

Avoid

  /* Example */
  function isSomeNumString(numString){
    return numString == 5;
  }

Score

  /* Example */
  function isSomeNumString(numString){
    return numString === '5';
  }

Broken Promises

Synopsis

Promises A+ are catching up on every major framework but developers are still stuck in the callback mindset. To make the most from promises they need to be used, or precisely, chained correctly.

Avoid

  /* 
  * Example 1 - Using Angular JS $http promises
  * */
  function getUsers(callback){
    $http.get('/users')
      .then(function(res){
        callback(res);
      });
  }

  getUsers(function(res){
    $scope.users = res.users;  
  });

  /* 
  * Example 2 - Using Native NodeJS promises
  * */
  function getEmployees(){
    return new Promise(function(resolve, reject){
      resolve(doSomething());
    });
  }

  function getData(callback){
    getEmployees()
      .then(function(res){
        callback(res);
      });
  }

  getData(function(res){
    console.log(res.employees);
  });

Score

  /* 
  * Example 1 - Using Angular JS $http promises
  * */
  function getUsers(){
    return $http.get('/users');
  }

  getUsers()
    .then(function(res){
      $scope.users = res.users;  
    });

  /* 
  * Example 2 - Using Native NodeJS promises
  * */
  function getEmployees(){
    return new Promise(function(resolve, reject){
      resolve(doSomething());
    });
  }

  function getData(){
    return getEmployees();
  }

  getData()
    .then(function(res){
      console.log(res.employees);
    });    

Contribution

Send in your PRs in the following pattern:

  • Let there be a pattern

js-code-smells's People

Contributors

mohuk avatar mashhoodr avatar

Stargazers

Artyom V. Gorchakov avatar Digi avatar Ian Trudel avatar plus avatar Ana Claudia avatar elaine mattos avatar Ajinkya Kulkarni avatar M T avatar Sapna Dhalor avatar  avatar  avatar Sachin Patel avatar Brian Davies avatar  avatar Darshan Patil avatar Kamalesh Dhayal avatar Kia. avatar Slava Yultyyev avatar Roniel avatar Isac Fadoni avatar Jeremy avatar akuma avatar Matt Masurka avatar Roger Albino avatar A. Dzulfikar Adi Putra avatar Richard Soni avatar escapar avatar RB avatar tiff avatar Utkarsh Bhatt avatar Syg avatar Aibol Kussain avatar Jonatas Santos avatar Miguel Queiroz avatar Jalal azimi avatar Peony Gerochi avatar Ruhee Dewji avatar Tiago Luiz Aguiar de Souza avatar  avatar Cory Preus avatar Catarina Machado avatar  avatar Raúl Moya Reyes avatar Denis Tokarev avatar Mike Cooper avatar Danny avatar Narain M. avatar Angus H. avatar Manoj avatar Victor avatar

Watchers

James Cloos avatar Umayr Shahid avatar  avatar  avatar  avatar

js-code-smells's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.