To be more specific, the intent (the what) is more explicit, not the method (the how).
That's what i understand "more high-level" to mean. It's also commonly refereed to as declarative. I've never heard it called "more explicit", because the entire point is to hide details.
For example, a LINQ where clause or the typical [...]
But what you are trying to do with a piece of code is very rarely to "filter" some list. What you are trying to do is something domain specific, like "find all the apples". So you still have to try and decipher what the code actually does.
In my example we might have something like
fruits.filter(x => x.type == APPLE)
It's not obvious what the purpose here is, all you've done is put the if you'd otherwise have in the loop in some strange function pointer. and at the same time you've made hand optimizing it impossible and any higher level reasoning about code flow is not also harder. It becomes much worse if you start calling other methods inside that lambda, since that messes with the flow completely.
You can implement this in two ways yourself, either you use a decorator, so an object that wraps the enumerable and selects only apples, which is pretty simple, and probably what linq does anyway.
foreach(auto fruit in fruits) {
if(fruit.type == APPLE)
apple.add(fruit);
}
That's pretty simple, and they say about as much about the problem as the filter does, but they also clearly show the runtime performance implications.
As for the "boilerplate", I'd say that all example here don't contain any boilerplate. Your problem literally is "walk through the list and select all the fruits that are apples. Or maybe "only return apples from the iterable". It's not boilerplate if it's literally your logic. It's just code.
1
u/Beaverman May 25 '19
How is it more explicit? It's way more explicit to just do the thing you want to do.
Yes, they are higher level. That doesn't make them good.
That's solved by for-each loops. They are pretty simple in their function, and easily understandable.
How is doing what you actually want to do boilerplate? If what you want to do is sum a set of numbers, then why not just sum those numbers?