Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
roth_stephan_clean_c20_sustainable_software_development_patt.pdf
Скачиваний:
29
Добавлен:
27.03.2023
Размер:
7.26 Mб
Скачать

Chapter 5 Advanced Concepts of Modern C++

This notation is familiar to physicists and other scientists and it’s even safer. With type-rich programming and user-defined literals, you are protected against assigning a literal expressing a value of seconds to a variable of type Force.

Force force1 = 3.0; Force force2 = 3.0_s; Force force3 = 3.0_N;

//Compile-time error!

//Compile-time error!

//Works!

It is, of course, also possible to use user-defined literals together with automatic type deduction and/or constant expressions:

auto force = 3.0_N;

constexpr auto acceleration = 100.0_ms2;

That’s pretty convenient and quite elegant, isn’t it? So, what follows is my advice for public interface design.

Tip  Create interfaces (APIs) that are strongly typed.

With other words, you should largely avoid general, low-level built-in types, like int, double, or—at worst—void*, in public interfaces and APIs. Such non-semantic types are dangerous under certain circumstances, because they can represent just about anything.

Tip  There are some template-based libraries available that provide types for physical quantities, including all SI units. A well-known example is Boost.Units (part of Boost since version 1.36.0; see http://www.boost.org). And with the UNITS project, a header-only library developed by Nic Holthaus is available on GitHub (https://github.com/nholthaus/units) that provides a set of data types, containers, and traits for physical quantities.

Know Your Libraries

Have you ever heard of the “Not invented here” (NIH) syndrome? It is an organizational anti-pattern. The NIH syndrome is a derogatory term for a stance in many development organizations that describes the ignoring of existing knowledge or tried-and-tested solutions based on their place of origin. It is a form of “reinventing the wheel,” that

182