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

Chapter 4 Basics of Clean C++

Can you see how much clarity a small change like this could bring to your code? We introduced a small member function that explains its intention by its semantic name. And at the place where the string operation originally could be found, we’ve replaced the direct invocation of std::string::substr() by a call of the new function.

Note  The name of a function should express its intention/purpose, and not explain how it works.

How the job is done—that’s what you should learn from the code in the function’s body. Don’t explain the how in a function’s name. Instead, express the purpose of the function from a business perspective.

In addition, we have another advantage. The partial functionality of how the header is extracted from the HTML page has been quasi-isolated and is now more easily replaceable without fumbling around at those places where the function is called.

Parameters and Return Values

After we discussed function names in detail, there is another aspect that is important for good and clean functions: the function’s parameters and return values. These both also contribute significantly to the fact that a function or method can be well understood and is easily usable by clients.

Number ofParameters

How many parameters should a function or method have at most? Two? Three? Or just one?

Well, methods of a class often have no parameter at all. The explanation for this is that these always have an additional implicit “argumentavailable: this! The this pointer represents the context of execution. With the help of this, a member function

can access the attributes of its class, read, or manipulate them. In other words, from the perspective of a member function, attributes of a class feel like global variables.

When we think of a function in the pure mathematical sense (y = f(x)), it always has at least one parameter (see Chapter 7 about functional programming).

But why are too many parameters bad?

98

Chapter 4 Basics of Clean C++

First, every parameter in a function’s parameter list can lead to a dependency, with the exception of parameters of standard built-in types like int or double. If you use a complex type (e.g., a class) in a function’s parameter list, your code depends on that type. The header file containing the used type must be included.

Furthermore, every parameter must be processed somewhere inside of a function (if not, it is unnecessary and should be deleted immediately). Three parameters can lead to a relatively complex function, as we have seen by example of member function

BasicFrame::QueryFileName() from Apache’s OpenOffice.

In procedural programming it may sometimes be very difficult not to exceed

three parameters. In C, for instance, you will often see functions with more parameters. A deterrent example is the hopelessly antiquated Windows Win32 API, as shown in Listing 4-23.

Listing 4-23.  The Win32 CreateWindowEx Function to Create Windows

HWND CreateWindowEx

(

DWORD dwExStyle, LPCTSTR lpClassName, LPCTSTR lpWindowName, DWORD dwStyle,

int x, int y,

int nWidth, int nHeight,

HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam

);

Well, this ugly code comes from ancient times, obviously. I’m pretty sure that if it were designed nowadays, the Windows API would not look like that any more. Not

without reason, there are numerous frameworks, such as Microsoft Foundation Classes

(MFC), Qt (https://www.qt.io), and wxWidgets (https://www.wxwidgets.org), that wrap this creepy interface and offer simpler and more object-oriented ways to create a graphical user interface (UI).

99

Chapter 4 Basics of Clean C++

And there are few possibilities to reduce the number of parameters. You could combine x, y, nWidth, and nHeight to a new structure named Rectangle, but then there are still nine parameters. An aggravating factor is that some of the parameters of this function are pointers to other complex structures, which for their part are composed of many attributes.

In good object-oriented designs, such long parameter lists are usually not required. But C++ is not a pure object-oriented language, such as Java or C#. In Java, everything must be embedded in a class, which sometimes leads to much boilerplate code. In C++ this is not required. You are allowed to implement free-standing functions in C++, that is, functions that are not members of a class. And that’s quite okay.

Tip  Methods and functions should have as few parameters as possible. One parameter is the ideal number. Member functions (methods) of a class sometimes have no parameters at all. Usually those functions manipulate the internal state of the object, or they are used to query something from the object.

Avoid Flag Parameters

A flag parameter is a kind of parameter that tells a function to perform a different operation depending on its value. Flag parameters are mostly of type bool, and sometimes even an enumeration. See Listing 4-24.

Listing 4-24.  A Flag Parameter to Control the Level of Detail on an Invoice

Invoice Billing::createInvoice(const BookingItems& items, const bool withDetails) {

if (withDetails) { //...

} else { //...

}

}

The basic problem with flag parameters is that you introduce two (or sometimes even more) paths through your function and hence increase its cyclomatic complexity.

100

Chapter 4 Basics of Clean C++

The value of such a parameter is typically evaluated somewhere inside the function in an if or switch/case statement. It is used to determine whether to take a certain action. It means that the function is not doing one thing exactly right, as it should be (see the section “One Thing, No More,” earlier in this chapter). It’s a case of weak cohesion (see Chapter 3) and violates the single responsibility principle (see Chapter 6 about object orientation).

And if you see the function call somewhere in the code, you do not know exactly what a true or false means without analyzing the Billing::createInvoice()function in detail. See Listing 4-25.

Listing 4-25.  Baffling: What Does the True in the Argument List Mean?

Billing billing;

Invoice invoice = billing.createInvoice(bookingItems, true);

My advice is that you should simply avoid flag parameters. Such kinds of parameters are always necessary if the concern of performing an action is not separated from its configuration.

One solution could be to provide separate, well-named functions instead, as shown in Listing 4-26.

Listing 4-26.  Easier to Comprehend: Two Member Functions with Intention-­ Revealing Names

Invoice Billing::createSimpleInvoice(const BookingItems& items) { //...

}

Invoice Billing::createInvoiceWithDetails(const BookingItems& items) { Invoice invoice = createSimpleInvoice(items);

//...add details to the invoice...

}

Another solution is a specialization hierarchy of billings, as shown in Listing 4-27.

101

Chapter 4 Basics of Clean C++

Listing 4-27.  Different Levels of Details for Invoices, Realized the Object-Oriented Way

class Billing { public:

virtual Invoice createInvoice(const BookingItems& items) = 0; // ...

};

class SimpleBilling : public Billing { public:

Invoice createInvoice(const BookingItems& items) override; // ...

};

class DetailedBilling : public Billing { public:

Invoice createInvoice(const BookingItems& items) override; // ...

private:

SimpleBilling simpleBilling;

};

The private member variable of type SimpleBilling is required in the DetailedBilling class to be able to first perform a simple invoice creation without code duplication, and to add the details to the invoice afterward.

OVERRIDE SPECIFIER [C++11]

Since C++11, it can explicitly be specified that a virtual function should override a base class virtual function. For this purpose, the override identifier has been introduced.

If override appears immediately after the declaration of a member function, the compiler will check that the function is virtual and is overriding a virtual function from a base class. Thus, developers are protected from subtle errors that can arise when they merely think that they have overridden a virtual function, but in fact they have altered/added a new function, for example, due to a typo.

102