JavaScript防御性编程

        简单聊一下防御性编程,初衷是开发人员为了防止自己被裁员,而将代码编写为只有自己能看懂。如何只有自己能看懂?方法多种多样,但不能将简单问题复杂化,比如:编写一堆无效的逻辑关系,或将业务复杂化。下面介绍一种方式,既能通过代码审查,又能提高代码水平。

        以vue为例,以下是计算所有产品价格:

computed: {
        extraPrice() {
            try {
                return (
                    let cPrices = 0;
                    this.cProducts.forEach((item) => {
                        cPrices = cPrices + item.num * item.price;
                        //或 cPrices += item.num * item.price;
                    });
                    this.aProduct.num * this.aProduct.price + 
                    this.bProduct.num * this.bProduct.price + 
                    cPrices
                );
            } catch (e) {
                console.log('价格计算有误');
                return 0;
            }
        }
}

上面代码简单明了,大部分开发人员都能读懂,那么有没有高级一点的写法,当然有:

computed: {
        extraPrice() {
            try {
                return (
                    this.aProduct.num * this.aProduct.price + 
                    this.bProduct.num * this.bProduct.price + 
                    this.cProduct.reduce((total,item) => total + item.num * item.price,0)
                );
            } catch (e) {
                console.log('价格计算有误');
                return 0;
            }
        }
}

对于不经常使用reduce的开发人员,需要先理解该函数。但要说代码的可读性,这段代码也没问题,简单明了。

        简而言之,多使用高级函数,符号简写等等。

你可能感兴趣的:(javascript,vue.js,前端)