onsdag 18 maj 2011

Why I've stopped liking C++ algorithms

I have usually been an advocate for using STL-style algorithms in C++ for as much as possible when working with containers. And if you read C++ books and listen to the gurus, they promote them constantly. However, some days ago a friend asked me about some fairly simple code I had written using a find_if algorithm (making use of C++0x):

auto it = find_if(m_tags.begin(), m_tags.end(), bind(&tag_data::find_by_name, placeholders::_1, name_to_search));

And the function (which must be a member function in this case):

bool tag_data::find_by_name(const std::string& name)
{
if (name == m_name)
return true;
else
return false;
}

Now, an algorithm doesn't often get shorter than this. And still my friend (fairly new to C++) had a hard time grasping what was going on, which I can understand.

And I realized that in many ways algorithms do break two of the most fundamental programming design rules:

Write once, read many times.
Code is written once, but will be read multiple times, sometimes by colleauges who do not use C++ as their primary language. And lets face it, even simple algorithms are often harder to understand than a good-old for-loop. I thought so when I was new to C++ and I think that goes for most people (be honest now). I also think that the time you save writing algorithm-style over for-loop style is quite minimal.

Expose as little of your internals as possibly.
To avoid polluting your scope, you should always declare members as local and as private as possible.

However, a problem with C++ is that there are no real private members as in some other languages. Even though private members are inaccessible from the outside, they are still visible from the outside, which is a bit of a problem today when most people uses code completion tool extensively.

In the example above, I only use find_by_name in one place in the code, so I would've liked to make it not only private, but local to the caller function. This has not been possible before lambas was introduced in C++0x. And still the problem is that many people don't use lambas and it will probably take a long time until we see them adopted by the masses. Bottom line: Algorithms risks polluting your scope if you dont use fancy new (still experimental) C++ stuff.

Inga kommentarer:

Skicka en kommentar