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

Chapter 9 Design Patterns and Idioms

return {};

}

}

};

At the call site of the function, you now have two ways to handle the return value, as illustrated in the following example:

int main() {

CustomerRepository repository { };

auto optionalCustomer = repository.findCustomerByName("John Doe");

//Option 1: Catch an exception, if 'optionalCustomer' is empty try {

auto customer = optionalCustomer.value(); } catch (std::bad_optional_access& ex) {

std::cerr << ex.what() << std::endl;

}

//Option 2: Provide a substitute for a possibly missing object auto customer = optionalCustomer.value_or(NotFoundCustomer());

return 0;

}

In the second option, for instance, it is possible to either provide a standard (default) customer, or—as in this case—an instance of a special case object, if optionalCustomer is empty.

I recommend choosing the first option when the absence of an object is unexpected and is a clue that a serious error must have been occurred. For the other cases, where a missing object is nothing unusual, I recommend option 2.

What Is an Idiom?

A programming idiom is a special kind of pattern to solve a problem in a specific programming language or technology. That is, unlike the more general design patterns, idioms are limited in their applicability. Often, their applicability is limited to exactly one specific programming language or a certain technology, for example, a framework.

435