|
I struggle to think of real-world examples where I've just needed to chain and chain and chain values of different types more than a handful of times. The claimed need for the pipe operator is this construction: function bakeCake() {
return separateFromPan(coolOff(bake(pour(mix(gatherIngredients(), bowl), pan), 350, 45), 30));
}
The piped code looks like: function bakeCake() {
return gatherIngredients()
|> mix(%, bowl)
|> pour(%, pan)
|> bake(%, 350, 45)
|> coolOff(%)
|> separateFromPan(%)
;
Which is... fine? It certainly looks better than the mess we started with, but adding names here only helps clarify each step. function bakeCake() {
const ingredients = gatherIngredients();
const batter = mix(ingredients);
const batterInPan = pour(batter, pan);
const bakedCake = bake(batterInPan, 350, 45);
const cooledCake = coolOff(bakedInPan);
return separateFromPan(cooledCake);
}
Even if you consider the `const` to be visual noise, the names are useful. At any point you can understand the goal of the code on the right-hand side by looking at the name of the variable on the left-hand side. You can also visually scan the right-hand side and see the processing steps. You can also introduce new steps to the control flow at any point and understand what the data should look like both before and after your new step.I agree that the the control flow is more clearly elucidated in the pipe operator example, but it tosses away useful information about the state that the named variables contain. It also introduces two new syntactical concepts for your brain to interpret (the pipe operator and the value placeholder). I contend the cognitive load is no greater in the example with names, and the maintainability is greatly improved. If you have an example where there are dozens of steps to the control flow with no break, I'd be really curious to see it. |
1. Gather the ingredients, mix them in a bowl, pour into a pan, bake at 350 degrees for 45 minutes, let it cool off and then separate it from the pan.
2. Get ingredients by gathering the ingredients. Make batter by mixing the ingredients. Make batter in a pan by pouring the batter in a pan. Make a baked cake by baking the batter in the pan at 350 degrees for 45 minutes. Make a cooled cake by cooling the baked cake. Separate it from the pan.
For me personally #1 is more readable because #2 is unnecessarily bloated with redundantly described subjects.