Skip to content
This repository has been archived by the owner on Oct 5, 2021. It is now read-only.

Developer best practices

NatashaWso2 edited this page Nov 20, 2017 · 3 revisions

Promises

Don’t use new Promise unnecessarily

When calling a promise based api we can directly pass the returned promise to the callee of our function. No need of creating a new Promise object. We only need new Promise when creating a Promise based API with a callback/event etc based API.

eg:

No:

return new Promise((resolve, reject) => {
    axios.post(endpoint, payload, { headers })
        .then((response) => {
            resolve(response.data);
        }).catch(error => reject(error));
    });

Yes:

return axios.post(endpoint, payload, { headers });

Chain Promise based asynchronous API calls

An attractive feature of Promises is its ability to avoid callback hell. But nested then() method calls takes away this advantage.

Instead of nesting then calls use promise chaining.

No:

api().then(function(result){
     api2().then(function(result2){
          api3().then(function(result3){
               // do work
          });
     });
});

Yes:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
});

This avoids code lines going deep into extra indentation levels.

React

Don't directly manipulate React state.

Instead always use setState. See linked documentation for the reasons. No:

this.state.name = 'John'

Yes:

this.setState({name: 'John'});

Use absolute paths to import modules

Modules are a group of code providing discreet independent set of functionality. We are still in the process of identifying which parts of the code should be separate modules. So this is not a hard rule :) But generally prefer absolute paths.

Examples for modules: langserver, api-client, expression-editor

These modules can be accessed by absolute paths.

Advantage of this is that in addition to looking nicer, these modules can be moved around when needed ( in a refactoring for example ) and the import paths won’t be affected.

No:

import ExpressionEditor from '../../../../../../expression-editor/expression-editor-utils';

Yes:

import ExpressionEditor from 'expression-editor/expression-editor-utils';