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

Chapter 6 Modularization

Figure 6-6.  The impact of circular dependencies between classes in different components

The Customer and Account classes are each located in different components. Perhaps there are many more classes in each of these components, but these two classes have a circular dependency. The consequence is that this circular dependency has a impact on the architectural level. The circular dependency at the class level leads to

a circular dependency at the component level. CustomerManagement and Accounting are tightly coupled (remember the section about loose coupling in Chapter 3) and cannot be reused independently. And of course, also, an independent component test is not possible anymore. The modularization on architecture level has been practically reduced to absurdity.

The acyclic dependency principle states that the dependency graph of components or classes should have no cycles. Circular dependencies are a bad form of tight coupling and should be avoided at all costs.

Don’t sweat it! It is always possible to break a circular dependency, and the following section will show you how to avoid or break them.

Dependency Inversion Principle (DIP)

In the previous section, we experienced that circular dependencies are bad and should be avoided under all circumstances. As with many other problems related to unwanted dependencies, the concept of the interface (in C++, interfaces are simulated using abstract classes) is our friend when dealing with such troubles.

262

Chapter 6 Modularization

The goal should therefore be to break the circular dependency without losing the necessary possibility that the Customer class can access the Account class and vice versa.

The first step is that we no longer allow one of the two classes to have direct access to the other class. Instead we allow access only via an interface. Basically, it does not matter from which one of classes (Customer or Account) the interface is extracted. I’ve decided to extract an interface named Owner from Customer. Exemplary, the Owner interface declares just one pure virtual member function, which must be overridden by classes that implement this interface. See Listings 6-22 and 6-23.

Listing 6-22.  An Exemplary Implementation of the New interface Owner (Owner.h)

#pragma once

#include <memory> #include <string>

class Owner { public:

virtual ~Owner() = default;

virtual std::string getName() const = 0;

};

using OwnerPtr = std::shared_ptr<Owner>;

Listing 6-23.  The Customer Class Implements the Owner Interface (Customer.h)

#pragma once

#include "Owner.h" #include "Account.h"

class Customer : public Owner { public:

void setAccount(AccountPtr account) { account_ = account;

}

263

Chapter 6 Modularization

std::string getName() const override {

// return the Customer's name here...

}

// ...

private:

AccountPtr account_; // ...

};

using CustomerPtr = std::shared_ptr<Customer>;

As can easily be seen, the Customer class still knows its Account. But when we take a look at the changed implementation of the Account class, there is no dependency to Customer anymore. See Listing 6-24.

Listing 6-24.  The Changed Implementation of the Account Class (Account.h)

#pragma once

#include "Owner.h"

class Account { public:

void setOwner(OwnerPtr owner) { owner_ = owner;

}

//...

private:

OwnerPtr owner_;

};

using AccountPtr = std::shared_ptr<Account>;

Depicted as an UML class diagram, the changed design at class level is shown in Figure 6-7.

264

Chapter 6 Modularization

Figure 6-7.  Adding the interface has eliminated the circular dependency on class level

Excellent! With this first step in the redesign, there are no more circular dependencies at the class level. The Account class knows absolutely nothing about the Customer class. But how does the situation look from the component level, as depicted in Figure 6-8?

Figure 6-8.  The circular dependency between the components is still there

265

Chapter 6 Modularization

Unfortunately, the circular dependency between the components has not been broken. The two association relationships still go from one element in the one component to one element in the other component. However, the step to achieve this goal is blindingly easy: we need to relocate the Owner interface to the other component, as depicted in Figure 6-9.

Figure 6-9.  Relocating the interface also fixes the circular dependency problem at the architecture level

Great! The circular dependencies between the components have disappeared. The Accounting component is no longer dependent on CustomerManagement, and as a result, the quality of the modularization has been significantly improved. Furthermore, the Accounting component can now be tested independently.

In fact, the bad dependency between both components was not literally eliminated. On the contrary, through the introduction of the Owner interface, we have one additional dependency at the class level. What we really have done is invert the dependency.

The dependency inversion principle (DIP) is an object-oriented design principle that decouples software modules. The principle states that the basis of an object-oriented design is not the special properties of concrete software modules. Instead, their common

266

Chapter 6 Modularization

features should be consolidated in a shared used abstraction (e.g., an interface). Robert C. Martin a.k.a. “Uncle Bob,” formulated the principle as follows:

“A. High-level modules should not depend on low-level modules. Both should depend on abstractions.

B. Abstractions should not depend on details. Details should depend on abstractions.”

—Robert C. Martin [Martin03]

Note  The terms “high-level modules” and “low-level modules” in this quote can be misleading. They refer not necessarily to their conceptual position within a layered architecture. A high-level module in this particular case is a software module that requires external services from another module, the so-called low-­ level module. High-level modules are those where an action is invoked; low-level modules are the ones where the action is performed. In some cases, these two categories may also be located on different levels of a software architecture (e.g., layers), or as in our example in different components.

The principle of dependency inversion is fundamental for what is perceived as a good object-oriented design. It fosters the development of reusable software modules by defining the provided and required external services solely through abstractions (e.g., interfaces). Consistently applied to our discussed case, we would also have to redesign the direct dependency between the Customer and the Account accordingly, as depicted in Figure 6-10.

267

Chapter 6 Modularization

Figure 6-10.  Dependency inversion principle applied

The classes in both components are solely dependent on abstractions. Therefore, it is no longer important to the client of the Accounting component which class requires the Owner interface or provides the Account interface (remember the section about information hiding in Chapter 3). I have insinuated this circumstance by introducing a class that is named AnyClass, which implements Account and uses Owner.

For instance, if we have to change or replace the Customer class now, for example, because we want to mount the Accounting against a test fixture for component testing, then nothing has to be changed in the AnyClass class to achieve it. This also applies to the reverse case.

The dependency inversion principle allows software developers to design dependencies between modules purposefully, that is, to define in which direction dependencies are pointing. You want to inverse the dependency between the components, that is, Accounting should be dependent on CustomerManagement? No problem: simply relocate both interfaces from Accounting to the CustomerManagement and the dependency turns around. Bad dependencies, which reduce the maintainability and the testability of the code, can be elegantly redesigned and reduced.

268