I write a lot of C++ code at my day job, so often I don’t want to do that for my hobby projects. There’s a lot of complexity in C++, no doubt. However, I think many of troubles of C++ are simply bad API designs.
As just an example, let’s look at the std::map API. I mean, really?
OK… so there are some things we know about a map, but the most important is that the key values are unique. That is, if “name” exists, there will be one and only one of them.
So what the flip is up with the iterator stuff? And why on earth is there a count() function instead of just a contains() function?
I’m sure there is some explanation for it, but I’m not terribly interested in it. As a consumer of the API, I don’t really care why you make my life more challenging. I want to work with nice, clean APIs.
Swift vs. C++
Part of what make Swift look more appealing is the clean syntax and sometimes better (though, there are many examples where this isn’t the case today) API interfaces. Let’s take a look at a snippet of a Vapor project I’m toying around with:
That’s some pretty reasonable code. Maybe I’d change a few things, but there’s nothing that makes me go, “what the heck is wrong with you?”
Compare that to what it might look like in straight up C++:
I mean… it’s not that terrible, but there is a lot of WTF? in there. The biggest problem is that these APIs cause the code to really switch context from the get() handling to the details of parsing out data. That’s not cool.
We can fix this though and create something that is much more easier to follow and use:
This would be the same exact number of lines of code as the Swift version if I change the Swift version to not throw on an error trying to get the parameter. But more importantly, we didn’t lose anything in the C++ version. However, we did gain code that is much easier to read and maintain.
Build better APIs, your code and coworkers will thank you for it.