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的开发人员,需要先理解该函数。但要说代码的可读性,这段代码也没问题,简单明了。

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

相关推荐
shoubepatien1 分钟前
JavaWeb_Web基础
java·开发语言·前端·数据库·intellij-idea
WordPress学习笔记9 分钟前
wordpress外贸主题Google地图添加(替换)方案
前端·wordpress·wordpress地图
计算机毕设VX:Fegn089514 分钟前
计算机毕业设计|基于springboot + vue旅游信息推荐系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·课程设计·旅游
OrangeForce18 分钟前
Monknow新标签页数据导出
javascript·edge浏览器
小妖66634 分钟前
力扣(LeetCode)- 93. 复原 IP 地址(JavaScript)
javascript·tcp/ip·leetcode
古月฿1 小时前
大学生素质测评系统设计与实现
java·vue.js·redis·mysql·spring·毕业设计
码农秋1 小时前
Element Plus DatePicker 日期少一天问题:时区解析陷阱与解决方案
前端·vue.js·elementui·dayjs
未来之窗软件服务1 小时前
未来之窗昭和仙君(五十六)页面_预览模式——东方仙盟筑基期
前端·仙盟创梦ide·东方仙盟·昭和仙君·东方仙盟架构
top_designer1 小时前
Illustrato:钢笔工具“退休”了?Text to Vector 零基础矢量生成流
前端·ui·aigc·交互·ux·设计师·平面设计
源码获取_wx:Fegn08951 小时前
基于springboot + vue物业管理系统
java·开发语言·vue.js·spring boot·后端·spring·课程设计