11

不写容易出错的代码

 3 years ago
source link: https://blog.csdn.net/21aspnet/article/details/114987553
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

不写容易出错的代码

21aspnet 2021-03-18 18:38:05 2173

下面2段代码都是完成商品名称的更新,只是第一种情况数据源是list第二种是map

第一代代码是从List里获取第0个

entity.setProduct_name(productList.get(0).getName());

第二段代码从map里获取键值

entity.setProduct_name(productMap.get(pid).getName()));

如果哪一天第一段代码修改了  然后忘记改第二段代码这是一种容易犯错的情况。

更多的是改了第一段代码直接复制到第二段,也可以运行但是就错了。

所以避免这种问题的出现你需要把这种get定义为一个对象,然后set的时候都一样。

更好的是这2段代码最好是封装一个方法。

因为这里不会随便改变,改变的是下面的获取里面的name等属性。

这样2段设置商品属性的代码都是:

entity.setProduct_name(product.getName());

所以封装的核心思想是:减少差异,从2到1!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK