Sometimes, a for loop is best

It can feel polished to always use a functional style. In Rust, for example, programmers often use .map(|x| { ... }) to apply a transformation to the data being processed. This is generally an elegant idiom, but can feel forced.

Creating an inner closure adds syntactic noise to the program via the vertical bars, and new variable name(s).

Taking advantage of .map() and its uncommonly seen cousin .for_each() can lead to somewhat hostile style. It forces programmers that mostly used imperative languages, such as Java and Go, to spend extra time to parse and interpret your intent.

If you’re applying a complex transformation, consider sticking with a for loop. You’ll feel less fancy, but your code will be simpler.

1 note

  1. tim-mcnamara posted this