如何写出低质量代码

81 阅读2分钟

要写出高质量代码,首先要知道哪些是低质量代码。本文从团队实际代码为例,讲述如何写出低质量代码,原理/原因分析,顺便说下如何提高B格,变为高质量代码。废话少说,开喷~

首先,先来几个实例

原代码
calculateQuotaGap() {
    if (this.dialogForm.quota === undefined) {
        this.dialogForm.quotaGap = compute.accSub(0, Number(this.dialogForm.carbonEmission))
    }
    if (this.dialogForm.carbonEmission === undefined) {
        this.dialogForm.quotaGap = compute.accSub(Number(this.dialogForm.quota), 0)
    }
    if (this.dialogForm.quota !== undefined && this.dialogForm.carbonEmission !== undefined) {
        this.dialogForm.quotaGap = compute.accSub(Number(this.dialogForm.quota), Number(this.dialogForm.carbonEmission))
    }
},
优化后
calculateQuotaGap() {
    const quota = Number(this.dialogForm.quota) || 0;
    const carbonEmission = Number(this.dialogForm.carbonEmission) || 0;
    this.dialogForm.quotaGap = compute.accSub(quota, carbonEmission);
}

原因分析

不会封装,this.dialogForm在一个10行的函数里都出现 11次了


原代码
this.$refs["queryForm"].validate(valid => {
    if (valid) {
      // 执行查询操作
      let params = {
        ...this.queryParams,
        date: this.queryParams.date ? typeof this.queryParams.date === 'object' ? `${this.queryParams.date.getFullYear()}` : this.queryParams.date : this.queryParams.date,
      }
    }
  });
优化后
this.$refs["queryForm"].validate(valid = >{
    if (valid) {
        const { date, ...restParams } = this.queryParams;
        const formattedDate = date instanceof Date ? `$ {
            date.getFullYear()
        }`: date;

        const params = {...restParams, date: formattedDate || date};
    }
});
原因分析

不会解构赋值,不会判断日期,不会判断空值


原代码1
getList() {
    this.loading = true
    this.$api.get('/api/simulation/asset/list', this.queryParams).then(res => {
        this.tableData = res.rows
        this.total = res.total
        this.loading = false
    })
}
原代码2
getList() {
    this.loading = true
    this.$axios.get('', {
        params: this.queryParams
    }).then(res => {
        this.loading = false
        this.tableData = res.data.rows
        this.total = res.data.total
    }).catch(err => {
        this.loading = false
    })
},
优化后
getList() {
    this.loading = true;
    this.$api.get('/api/simulation/asset/list', this.queryParams).then(res = >{
        this.tableData = res.rows;
        this.total = res.total;
    }).
    finally(() = >{
        this.loading = false;
    });
}
原因分析:

不熟悉promise的finally方法,then和catch里重复执行 this.loading = false


原代码
// 获取不同情景下的预测数据
getChartData() {
  switch (this.selectedOption) {
    case 1:
      this.chartData.min = 0;
      this.chartData.max = 400;
      this.chartData.interval = 100;
      this.chartData.label = "基准情景";
      return;
    case 2:
      this.chartData.min = 0;
      this.chartData.max = 600;
      this.chartData.interval = 100;
      this.chartData.label = "强化总量控制情景";
      return;
    default:
      return [];
  }
},
优化后
getChartData() {
    const scenarios = {
        1 : {
            min: 0,
            max: 400,
            interval: 100,
            label: "基准情景"
        },
        2 : {
            min: 0,
            max: 600,
            interval: 100,
            label: "强化总量控制情景"
        },
    };

    const scenario = scenarios[this.selectedOption];

    if (scenario) {
        this.chartData.min = scenario.min;
        this.chartData.max = scenario.max;
        this.chartData.interval = scenario.interval;
        this.chartData.label = scenario.label;
    } else {
        // 可选: 清空或重置数据
        this.chartData = {};
    }
},

原因分析

没有代码可读性、可维护性概念


原代码

超大背景图 image.png

优化后

只有原来的30%大小,压缩了70%!而且是无损压缩

image.png

原因分析

没有性能优化的概念,图片压缩可以用 tinypng.com/


原代码
import * as echarts from 'echarts';
优化后
import { init } from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
原因分析

没有性能优化的概念,没必要将整个 echarts 包全部引入,因为 echarts 库比较大,可能会增加不必要的负担。我们可以通过按需引入的方式,减少包的体积,从而提升性能。


今天就先写到这里吧, 下班了。明天写点通用的高/低质量代码对比