3 ms·
There's no question which order to perform the map and select in the given example, there's no decision to make. You can't do the select until after the map bec
by Jtsummers 7y ago
There's no question which order to perform the map and select in the given example, there's no decision to make. You can't do the select until after the map because you're selecting based on the results of the map. If it weren't ruby, it would be obvious by the types in a language with a static type system.
Of course the same is true in the for-loop example. But overall, there are more things to specify in the for-loop:
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;
Specify:
- storage location for result
- loop variable
- loop variable initial value
- terminating condition (is it < or <=?)
- increment
- temp variable for producing ids
- test condition for filtering
- how to add new item to result
return (1..5)
.map{|n| "car-#{n}"}
.select{|m| car_is_empty(m)}
Specify:
- min value of range
- max value of range (are ranges inclusive or exclusive?)
- how to generate id
- how to query
Now, this is a trivial example. I wouldn't argue that either way is clearly better than the other in this particular case. But, in my experience and opinion, the latter is much better as things become more complex.
- meheleventyone 7y agoYou certainly have to be more explicit but I don’t think most of what you actually have to specify is that important. It’s a bog standard inclusive for loop after all. That’s the decision and it’s the same as deciding I need to generate an inclusive range iterator. I will give you there is more typing to mess up and therefore if you’re not testing perhaps an issue. But we are testing the things we write? Particularly when on one side of things you put inclusive and exclusive together with the max value of the range and on the other you separate them. IME this is basically horses for courses, some people will be at home with procedural syntax and other prefer using functional concepts.
- Jtsummers 7y agoThe inclusive/exclusive question is equivalent to asking if the terminating test should be with < or <=. I paired it that way deliberately.