DEV Community


On wrappers for standard library

voins profile image Alexey Voinov ・2 min read

Every language has a standard library. Everybody uses it. Not everybody likes it. There are a couple of problems with standard libraries: they have to satisfy everybody and they have to be compatible at least with couple of previous versions (well, if the language is worth using). Sometimes I cannot help but notice that I am writing the same code over and over again just because the standard library was designed that way long time ago and even though there are already new tools present they have to support compatibility. For example:

std::string::size_type p = filename.find_last_of(/.);
if (p != std::string::npos)
    // use p in some meaningful way

when there’s already std::optional<>, or

loglist_t::iterator i = loggers.find(name)
if (i != loggers.end())
    // dereference i and use the result



when there’s Optional::or() already, but my employer doesn’t plan to switch to Java 9. I would love to put those pieces of code into some small methods, but where should I place them?

There is actually a very simple solution to this problem. I was a bit surprised to find out that it is described in details in Uncle Bob’s “Clean Code” in chapter 8, but for some reason I’ve never seen this approach actually implemented. We just need to create wrappers for everything we use from the standard library, but everyone is busy creating alternative implementations instead. Let me tell you a secret: modern compilers are very good at optimisations and this wrapper will probably cost you nothing or almost nothing. All of sudden magic happens, and you have home for a bunch of utility methods you used to make static and put in OptionalUtil class, or you don’t care if your compiler renamed std::experimental::optional to std::optional, because only a single line will be changed in your application, or you can create better API for strings and utilise aforementioned std::optional, or you can implement methods from newer version of standard library and happily use it already, or … you name it.

The only drawback I see here is it’s very easy to get used to those wrappers, and when you move to another project, you’ll be missing them. But you already know what to do, don’t you?


Editor guide