Friday, 13 November 2009

Why people still don't use the STL

...because it is arbitrary, cryptic and seriously difficult to read.

Let's take a quick example, using std::map< filename,sample> m_samples:

 const BOOL AUDIO::is_playing(const FILENAME sound_file)
 {
  return (m_samples[sound_file].is_playing());
  }

works, but this doesn't:

 const BOOL AUDIO::is_playing(const FILENAME sound_file) const
 {
  return (m_samples[sound_file].is_playing());
 }

Why?

Well, std::map doesn't have an operator[] that returns constant references, of course. Gnngh.

No, you have to use this gem instead:

 const BOOL AUDIO::is_playing(const FILENAME sound_file) const
 {
  return (m_samples.find(sound_file)->second.is_playing();
 }

This forces you to use two major usability criminals, obfuscator-in-chief std::pair, which throws in a less-than-clear 'second', and partner-in-crime iterator, or in this case the snappily titled

 std::map< filename,sample>::iterator

Honestly. And oh noes! Heaven forbid you should want to use an STL container for storing resource classes as it unavoidably makes copies of things on insertion, so you'd better be using smart pointers or it'll be throwing things away left and right.

And another thing. Do you think it would be useful if a container class had a function called, oh I don't know, contains()? Nope. you have to cryptically look for something, and then compare it to an element off the end of the (not necessarily linear) container.

Good code:
 if (samples.contains(sound_file))
STL code:
 if (samples.find(sound_file) == samples.end())

Well, we could write our own contains() function by just extending the std::map, surely? But no! You can't inherit from STL objects.

And this is why STL is still widely ignored. It's useful, but that comes at the cost of code that will seriously slow down your reading if you ever want to come back to it.

No comments:

Post a Comment