Skip to content

Simplicity

"With constant pressure to add features and options and configurations, and to ship code quickly, it's easy to neglect simplicity, even though in the long run simplicity is the key to good software. Simplicity requires more work at the beginning of a project to reduce an idea to its essence and more discipline over the lifetime of a project to distinguish good changes from bad or pernicious ones. With sufficient effort, a good change can be accommodated without compromising what Fred Brooks called the 'conceptual integrity' of the design but a bad change cannot, and a pernicious change trades simplicity for its shallow cousin, convenience. Only through simplicity of design can a system remain stable, secure, and coherent as it grows." (Preface, The Go Programming Language)

Variadic templates with initializer lists

C++11 introduced variadic templates that can be used to define functions that take an arbitrary number of arguments like printf(). For example, here is a definition of a simple add function via a recursive template:


template <typename T>
T add(T arg) {
  return arg;
}

template <typename T, typename... Ts>
T add(T arg, Ts... args) {
  return arg + add(args...);
}
 

Another way to define the above add() function is via initializer lists without any recursion.


template <typename T, typename... Ts>
T add(T arg, Ts... args) {
  auto sum = arg;
  T values[] = {args...};
  for (auto v : values) {
      sum += v;
  }
  return sum;
}