Programming idioms introduction
What are programming idioms?
Articles in this series
- Idiom: regular data and functions
- Idiom: C API wrapper
- Idiom: Mockable interfaces
- Const ref member: No
- Const ref member: Yes
- The C.12 rule on const
- Programming idiom remarks
Also see the above in presentation form
Introduction
A native English speaker faced with “Counting and looking enjoyed are by little humans” might react “I get that children like playing hide-and-seek, but you made it way too complicated”. In natural language idiomatic usage is a particular, well understood way to communicate certain things, on top of basic language features like words, phrases, nouns, verbs etc.
A mature programming language has many features. I’m going to use C++ as an example, but the ideas apply elsewhere as well. For example there will features to customize data copying, destructors, make members public or private, different of passing arguments to a function etc.
A programming idiom is a group of detailed rules and choices that uses language features in a coherent, well understood way, in order to solve certain kinds of problems.
A mature programming language would support multiple idioms. Sample idioms that I’m going to cover here are:
- Regular data and functions
- C API wrapper
- Mockable interfaces
Idiomatic code follows the rules of one such idiom. Hopefully programmers than recognise the pattern and they can focus on the problem at hand without having to repeatedly justify the choices.
Compared with a paradigm such as object-oriented, functional, data-driven etc., an idiom goes into very specific details on how to use language features.
When a choice diverges from the idiomatic way, there could be several reasons that range from:
- There could be a good reason to do so. That might require some comment to explain the reason.
- It’s an incorrect choice. Despite that, it might be difficult to change due to a number of factors including existing legacy code.
However most of the divergence lives in the space in between, where suboptimal choices are made, the divergence is only partial, there is more to gain from adopting the idiom than from choosing the divergence, but the pain point is not enough for developers to adopt better habits.
Code convention/guidelines documents traditionally both helped and hurt the adoption of good rules. Their main problem is that they do not address explicitly multiple idioms handling language feature usage in the form “always do this, except here and here and here” or “don’t do this, except here and here”.
As we’ll see for the three idioms above: copy, move, equality and const are handled differently.
References
A lot of the ideas in this series of articles come from Elements of Programming by Alexander Stepanov and Paul McJones, a book that all programmers should read carefully (and almost nobody does).