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.


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

查看所有标签

猜你喜欢:

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

算法设计、分析与实现

算法设计、分析与实现

徐子珊 / 2012-10 / 65.00元

《算法设计、分析与实现:c、c++和java》由徐子珊编著,第1章~第6章按算法设计技巧分成渐增型算法、分治算法、动态规划算法、贪婪算法、回溯算法和图的搜索算法。每章针对一些经典问题给出解决问题的算法,并分析算法的时间复杂度。这样对于初学者来说,按照算法的设计方法划分,算法思想的阐述比较集中,有利于快速入门理解算法的精髓所在。一旦具备了算法设计的基本方法,按应用领域划分专题深入学习,读者可以结合已......一起来看看 《算法设计、分析与实现》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具