clean-style in your JS application

·

6 min read

JS is a flexible language to code, so we will bloat the whole project with lots of unclean-code. Through my several front-end coding years, I conclude few ways to optimize your codebase, make your project neat, maintainable and easy to read for others, including yourself in the future. Some tips are in Vue project, and this is not a comprehensive one. Hope you find them helpful. Without further ado, let's start.

1.Oftentimes, we will find long expression in some frameworks' templates, something like below:

<input
  :disabled="
    !code ||
      look ||
      form.getFieldValue(
        `preCondition.${index}-operator`
      ) === 'EXISTS'
  "
/>

Do you know what it aims to do? What if you need to tweak it because of some requirement changes? Annoying, right. Whenever you encounter such code, you need to optimize it, whether it's coded by yourself or other peers.

// in a .vue file
<input
  :disabled="shouldInputDisabled(index)"
/>

methods: {
  shouldInputDisabled(index) {
    const {
      schemaCode,
      look,
      form
    } = this;
    // console.log({ schemaCode, look, form });
    return !code ||
      look ||
      form.getFieldValue(
        `preCondition.${index}-operator`
      ) === "EXISTS";
  }
}

You could remove long expressions within template to methods or computed.First you could get a neat template, and more importantly, you can easily change it based on requirement changes, at the same time monitor the whole execution, such as console, debugger.

2.ES6/7/8+ provide more neat apis to optimize and simplify some execution, we need get up to date, use simple apis to make big optimization for your codebase.

<div
  v-if="
    item.propertyType == 'STRING' ||
      item.propertyType == 'SPU_REF' ||
      item.propertyType == 'SKU_REF'
  "
></div>

We know es6 has a Array.prototype.includes method, which can judge whether a variable is included in an array, so we can optimize above code to:

// in a .vue file
<div v-if="validatePropertyType(item.propertyType)"></div>

methods: {
  validatePropertyType(propertyType) {
    return ['STRING', 'SPU_REF', 'SKU_REF'].includes(propertyType);
  }
}

isn't it straightforward to read? It also reduces our code amount. Array.prototype.includes is not the only neat ones, es6/7/8...provides more apis to use.

3.Your code can describe the meaning, not your comments. So we should write self-explanatory code to structure our projects, and make efforts to reduce useless comments.

// in a method Object
// maybe some multiple lines of comments here to describe how it works, what it accomplishes
code() {
  let code = null;
  this.reportList.length && this.reportList.some(
    rsItem => rsItem.reportName === this.doldFileName.split('-')[0] && rsItem.sheetDtos.some(
      ssItem => {
        if (ssItem.sheetName === this.doldFileName.split('-')[1]) {
          code = ssItem.sheetSqlDto[0].code;
          return true;
        }
        return false;
      }
    )
  );
  return code;
}

This is something i have ever written. Do you know its intention at first glance? What about below one:

code() {
  const { reportList = [], doldFileName = '' } = this;
  if (!reportList.length) return null;
  const [reportName, sheetName] = doldFileName.split('-');
  const matchedRsItem = reportList.find(
    rsItem => rsItem.reportName === reportName
  );
  if (!matchedRsItem) return null;
  const matchedSsItem = matchedRsItem.find(
    ssItem => ssItem.sheetName === sheetName
  );
  if (!matchedSsItem) return null;
  return matchedSsItem.sheetSqlDto[0].code;
}

At least, I can easily understand every line of code, and it's target, compared with the above one, right? We should try our best to write clean-code, make our projects readable and maintainable. Comment is not the best explanation for our code.

4.Sometimes I need code some conditionals to fulfill my business flow. Maybe you ever saw below code sample:

if (text === 19) {
  return "生成";
} else if (text === 45) {
  return "制作";
} else if (text === 46) {
  return "异常";
} else if (text === 49) {
  return "完成";
} else if (text === 50) {
  return "失败";
} else if (text === 6) {
  return "待执行";
} else if (text === 16) {
  return "抽取中";
} else if (text === 17) {
  return "抽取异常";
} else {
  return "导出中";
}

Ooh, at least these codes can clearly express its result, but what about a better practice:

const { text = 11 } = arbitraryObject;
const statusStrMap = {
  19: "生成中",
  45: "制作中",
  46: "制作异常",
  50: "失败",
  49: "制作完成",
  6: "待执行"
};
return statusStrMap[text] || "defaultValue";

We can leverage polymorphism concept to optimize our conditionals, and this is a JS feature, maybe you cannot implement in other languages.

Conclusion
thank you for reading my first article about some practical ways to optimize our codebase. They can help make your project maintainable, readable, and easy to refactor. I'm not a native English-speaker, and maybe you cannot understand some statements, I'm sorry, I will work hard to nail it. Hope you enjoy it. Appreciate any comments and suggestions!