The Iterate-and-Mutate Programming Anti-Pattern

栏目: IT技术 · 发布时间: 5年前

内容简介:Take a look at this small, typical code snippet:I call this theThis is better for lots of reasons:

Take a look at this small, typical code snippet:

let car_ids = [];
for (let i = 1; i <= 5; i++) {
    const car_id = `car-${i}`;
    if (car_is_empty(car_id)) {
        car_ids.push(car_id);
    }
}
return car_ids;

I call this the iterate-and-mutate pattern. It comes up all the time in code. But every time we see it, we should think about replacing it with a mapping operation, like this: (Ruby syntax)

return (1..5)
         .map{|n| "car-#{n}"}
         .select{|m| car_is_empty(m)}

This is better for lots of reasons:

  • Code that mutates (changes) a variable is harder to reason about, and so easier to get wrong .
  • An explicit for loop is another common source of bugs.
  • The original snippet is longer because it’s doing boring, low-level work. More, boring, code is another source of bugs.
  • Long code with low-level operations like for loops and push ing values onto arrays is not expressive .
  • The shorter, functional version has no variables, no mutation, and no explicit looping. It’s much shorter and easy to understand, once you’ve seen this style.

Here’s a great intro to functional programming in Javascript.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

编程卓越之道

编程卓越之道

Hyde R / 韩东海 / 电子工业出版社 / 2006-4-1 / 49.80

各位程序员一定希望自己编写的代码是能让老板赞赏、满意的代码;是能让客户乐意掏钱购买的代码;是能让使用者顺利使用的代码;是能让同行欣赏赞誉的代码;是能让自己引以为豪的卓越代码。本书作者为希望能编写出卓越代码的人提供了自己积累的关于卓越编程的真知灼见。它弥补了计算机科学和工程课程中被忽略的一个部分——底层细节,而这正是构建卓越代码的基石。具体内容包括:计算机数据表示法,二进制数学运算与位运算,内存组织......一起来看看 《编程卓越之道》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

随机密码生成器
随机密码生成器

多种字符组合密码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具