Posts

Showing posts from February, 2024

Some Thoughts on Interfaces

  One principle that I have seen enunciated is that one should not have an interface with only one implementation. This is generally sensible. Why separate out an interface if there is no variation? You can get physical insulation without an interface, if you need one, using the PIMPL idiom. (This approach explicitly rejects the idea of creating an interface/implementation pair just because you expect a need to add another implementation in three months. Just be aware that coding in that context needs to be careful - the first time you create a class which owns an instance of the class with potential variation, and it doesn't do so through a pointer of some sort, you're adding more work than is necessary down the line when you suddenly need to be holding a pointer to an interface. My own view is that if you really know that a second implementation is barrelling down the tracks towards you, there's no reason not to put the eventually-required separation of responsibilities ...

Structured Bindings

Structured bindings tend to be dismissed in many discussions online as very minimal improvements to C++. There isn't very much you can do with them that's not on the package, so to speak: returning multiple values, iterating easily over maps, and initializing more than one variable in an if or switch scope. The point, however, is not what they allow you to do: everything you can do with them you can do without them. The point is how it is done. If we compare: auto [var, flag] = func(); with, say auto val = func(); auto var = val.first; auto flag = val.second; it's not just that we take one line instead of three to get the same result, it's that the latter code has to pay more attention to how rather than what. It draws attention to the fact that was was returned was a pair. There are at least three other possible mechanisms behind that first line. auto val = func(); auto var = val[0]; auto flag = val[1]; (an array) auto val = func(); auto var = get<0>(val); auto f...