Evolution of C++
It's a warm summer evening in 1998. If you asked me to write a method, that receives a reference to a list of integers, and should go through all of them and add a certain number to each and every one, this is how I would have solved it
Is it pretty? Probably not. But it gets the job done, it's not that complicated. Obviously there are some traps and possible sources for errors. I could have messed up the index etc. And I can hear all the people who would like to see C++ dead. This is way to much boiler plate, it's not "expressive" enough. And they are right. But again, this is 1998.
Now lets go to the year 2011 and take a look how we might do it then. Obviously we have the range based for loop (for each loop) at our disposal, which we could use, as we don't really care about the index value:
Looks nicer, doesn't it? The actual operation (add a number to items in the list) is much clearer, we don't have to worry about any issues with the index. It is guaranteed that every element of that list will be processed. Awesome.
The issue I have is that it is still a loop. So, unit testing this is not without its challanges, as getting certain coverage with a loop present is always a bit tricky.
The anwer is, let's make it modern, let's go to 2017. Now we get range algorithms. We can use the for each algorithm:
Recommended by LinkedIn
Now granted, this looks a little bit less nice than the for each loop we had before. However, this method can be very well tested. We are using a lambda statement to update each element.
Now let's make something fun. Let's add some concurreny. It is obvious that the operation (add the number) is independent among the items in the list. So we should be able to call this operation on several items all at once. This would seem like a big task to implement, thankfully the modern C++ algorithms are equipped with something called "Execution Policy".
And now, we just got fast:
All I did was to use the version of for_each that takes the execution policy argument. This one is very powerful. It runs concurrently AND uses SIMD (Single Instruction Multiple Data) to vectorize the operation in order to utilize the CPU even more.
Now I wonder, how is that for boiler plate? How many lines of code would you need in your preferred C++ killer language to concurrently iterate over a list like that?
And that was "up to date" 8 years ago. C++26 is around the corner and let me tell you, it's getting wild.
The answer is, in most modern languages you can get the same with mostly just a line of code. Which goes to show, there is not much difference it is mostly preference and, since we are human, bias.