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

Chapter 9 Design Patterns and Idioms

Special Case Object (Null Object)

In the section “Don’t Pass or Return 0 (NULL, nullptr)” in Chapter 4, you learned that returning a nullptr from a function or method is bad and should be avoided. There we also discussed various strategies to avoid regular (raw) pointers in a modern C++ program. In the section “An Exception Is an Exception, Literally!” in Chapter 5, you learned that exceptions should only be used for truly exceptional cases and not for the purpose of controlling the normal program flow.

The open and interesting question is now this: How do we treat special cases that are not real exceptions (e.g., a failed memory allocation), without using a non-semantic nullptr or other weird values?

Let’s pick up our code example again, which we have seen several times before: the query of a Customer by name. See Listing 9-40.

Listing 9-40.  A Lookup Method for Customers by Name

Customer CustomerService::findCustomerByName(const std::string& name) {

//Code that searches the customer by name...

//...but what shall we do, if a customer with the given name does not exist?!

}

Well, one possibility would be to return lists instead of a single instance. If the returned list is empty, the queried business object does not exist. See Listing 9-41.

Listing 9-41.  An Alternative to nullptr: Returning an Empty List if the Lookup for a Customer Fails

#include "Customer.h"

#include <vector>

using CustomerList = std::vector<Customer>;

CustomerList CustomerService::findCustomerByName(const std::string& name) {

//Code that searches the customer by name...

//...and if a customer with the given name does not exist: return CustomerList();

}

431

Chapter 9 Design Patterns and Idioms

The returned list can now be queried in the program sequence whether it is empty. But what semantics does an empty list have? Was an error responsible for the emptiness of the list? Well, the member function std::vector<T>::empty() cannot answer this question. Being empty is a state of a list, but this state has no domain-specific semantics.

Folks, no doubt, this solution is much better than returning a nullptr, but maybe not good enough in some cases. What would be much more comfortable is a return value that can be queried about its origination cause, and about what can be done with it. The answer is the Special Case pattern!

“A subclass that provides special behavior for particular cases.”

—Martin Fowler, Patterns of

Enterprise Application Architecture [Fowler02]

The idea behind the Special Case pattern is that we take advantage of polymorphism, and that we provide classes representing the special cases, instead of returning nullptr or some other odd value. These special case classes have the same interface as the “normal” class that is expected by the callers. The class diagram in Figure 9-14 depicts such a specialization.

Figure 9-14.  The class(es) representing a special case are derived from the Customer class

In C++ source code, an implementation of the Customer class and the NotFoundCustomer class representing the special case looks something like Listing 9-42 (only the relevant parts are shown).

432

Chapter 9 Design Patterns and Idioms

Listing 9-42.  An Excerpt from the Customer.h File with the Customer and NotFoundCustomer Classes

#ifndef CUSTOMER_H_ #define CUSTOMER_H_

#include "Address.h" #include "CustomerId.h"

#include <memory> #include <string>

class Customer { public:

// ...more member functions here...

virtual ~Customer() = default;

virtual bool isPersistable() const noexcept {

return (customerId.isValid() && ! forename.empty() && ! surname.empty()

&&

billingAddress->isValid() && shippingAddress->isValid());

}

private:

CustomerId customerId; std::string forename; std::string surname;

std::shared_ptr<Address> billingAddress; std::shared_ptr<Address> shippingAddress;

};

class NotFoundCustomer final : public Customer { public:

bool isPersistable() const noexcept override { return false;

}

};

using CustomerPtr = std::unique_ptr<Customer>;

#endif /* CUSTOMER_H_ */

433

Chapter 9 Design Patterns and Idioms

The objects that represent the special case can now be used largely as if they were valid (normal) instances of class Customer. Permanent null-checks, even when the object is passed around between different parts of the program, are superfluous, since there is always a valid object. Many things can be done with the NotFoundCustomer object, as if it were an instance of Customer, for example, presenting it in a user interface. The object can even reveal whether it is persistable. For the “real” Customer, this is done by analyzing its data fields. In the case of the NotFoundCustomer, however, this check always has a negative result.

Compared to the meaningless null-checks, a statement like the following one makes significantly more sense:

if (customer.isPersistable()) {

// ...write the customer to a database here...

}

STD::OPTIONAL<T> [C++17]

Since C++17, there is another interesting alternative that could be used for a possibly missing result or value: std::optional<T> (defined in the <optional> header). Instances of this class template represent an “optional contained value,” that is, a value that may or may not be present.

The Customer class can be used as an optional value using std::optional<T> by introducing a type alias as follows:

#include "Customer.h" #include <optional>

using OptionalCustomer = std::optional<Customer>;

Our search function CustomerService::findCustomerByName() can now be implemented as follows:

class CustomerRepository { public:

OptionalCustomer findCustomerByName(const std::string& name) { if ( /* the search was successful */ ) {

return Customer(); } else {

434