To make code easy to read and maintain, we should follow some best practices.

In this article, we’ll look at some best practices we should follow to make everyone’s lives easier.

Remove Duplicate Code

Duplicate code is bad.

If we have to change them, we’ve to change them in multiple places.

It’s easy to miss them.

Therefore, we should remove them.

For instance, instead of writing:

function showEmployeeList(employees) {
  employees.forEach(employee => {
    const salaries = employees.salaries();
    const tasks = employees.tasks();
    const data = {
      salaries,
      tasks
    };
    display(data);
  });
}
function showManagerList(managers) {
  managers.forEach(manager => {
    const salaries = manager.salaries();
    const tasks = manager.tasks();
    const data = {
      salaries,
      tasks
    };
    display(data);
  });
}

We write:

function showWorkersList(workers) {
  workers.forEach(worker => {
    const salaries = worker.salaries();
    const tasks = worker.tasks();

    const data = {
      salaries,
      tasks
    };

    switch (worker.type) {
      case "manager":
        render(data);
      case "employee":
        render(data);
    }
  });
}

Set Default Objects with Object.assign

Setting a non-empty object as the first argument of Object.assign will return an object with all the properties of the object in the first argument merged with the ones with the other arguments.

For instance, we can write:

const obj = Object.assign({
    title: "Foo"
  },
  config
);

obj is an object with the title with the properties in config after it.

#technology #programming #web-development #javascript #software-development

Complex and Duplicate Code and Functional Programming in JavaScript
1.80 GEEK