28
Incorporating Design Techniques and Frameworks

“I CAN NEVER REMEMBER HOW TO…”

Chapter 1 compares the size of the C standard to the size of the C++ standard. It is possible, and somewhat common, for a C programmer to memorize the entire C language. The keywords are few, the language features are minimal, and the behaviors are well defined. This is not the case with C++. Even C++ experts need to look things up sometimes. With that in mind, this section presents examples of coding techniques that are used in almost all C++ programs. When you remember the concept but forgot the syntax, turn to the following sections for a refresher.

…Write a Class

Don’t remember how to get started? No problem—here is the definition of a simple class:

#pragma once

// A simple class that illustrates class definition syntax.
class Simple
{
    public:
        Simple();                       // Constructor
        virtual ~Simple() = default;    // Defaulted virtual destructor

        // Disallow assignment and pass-by-value.
        Simple(const Simple& src) = delete;
        Simple& operator=(const Simple& rhs) = delete;

        // Explicitly default move constructor and move assignment operator.
        Simple(Simple&& src) = default;
        Simple& operator=(Simple&& rhs) = default;

        virtual void publicMethod();    // Public method
        int mPublicInteger;             // Public data member

    protected:
        virtual void protectedMethod(); // Protected method
        int mProtectedInteger = 41;     // Protected data member

    private:
        virtual void privateMethod();   // Private method
        int mPrivateInteger = 42;       // Private data member
        static const int kConstant = 2; // Private constant
        static int sStaticInt;          // Private static data member
};

As Chapter 10 explains, it’s a good idea to always make at least your destructor virtual in case someone wants to derive from your class. It’s allowed to leave the destructor non-virtual, but only if you mark your class as final so that no other classes can derive from it. If you only want to make your destructor virtual but you don’t need any code inside the destructor, then you can explicitly default it, as in the Simple class example.

This example also demonstrates that you can explicitly delete or default special member functions. The copy constructor and copy assignment operator are deleted to prevent assignment and pass-by-value, while the move constructor and move assignment operator are explicitly defaulted.

Next, here is the implementation, including the initialization of the static data member:

#include "Simple.h"

int Simple::sStaticInt = 0;   // Initialize static data member.

Simple::Simple() : mPublicInteger(40)
{
    // Implementation of constructor
}

void Simple::publicMethod() { /* Implementation of public method */ }

void Simple::protectedMethod() { /* Implementation of protected method */ }

void Simple::privateMethod() { /* Implementation of private method */ }

image With C++17, you can remove the initialization of sStaticInt from the source file if you make it an inline variable instead, initialized in the class definition as follows:

static inline int sStaticInt = 0;          // Private static data member

Chapters 8 and 9 provide all the details for writing your own classes.

…Derive from an Existing Class

To derive from an existing class, you declare a new class that is an extension of another class. Here is the definition for a class called DerivedSimple, which derives from Simple:

#pragma once

#include "Simple.h"

// A derived class of the Simple class.
class DerivedSimple : public Simple
{
    public:
        DerivedSimple();                      // Constructor

        virtual void publicMethod() override; // Overridden method
        virtual void anotherMethod();         // Added method
};

The implementation is as follows:

#include "DerivedSimple.h"

DerivedSimple::DerivedSimple() : Simple()
{
    // Implementation of constructor
}

void DerivedSimple::publicMethod()
{
    // Implementation of overridden method
    Simple::publicMethod(); // You can access base class implementations.
}

void DerivedSimple::anotherMethod()
{
    // Implementation of added method
}

Consult Chapter 10 for details on inheritance techniques.

…Use the Copy-and-Swap Idiom

The copy-and-swap idiom is discussed in detail in Chapter 9. It’s an idiom to implement a possibly throwing operation on an object with a strong exception-safety guarantee, that is, all-or-nothing. You simply create a copy of the object, modify that copy (can be a complex algorithm, possibly throwing exceptions), and finally, when no exceptions have been thrown, swap the copy with the original object. An assignment operator is an example of an operation for which you can use the copy-and-swap idiom. Your assignment operator first makes a local copy of the source object, then swaps this copy with the current object using only a non-throwing swap() implementation.

Here is a concise example of the copy-and-swap idiom used for a copy assignment operator. The class defines a copy constructor, a copy assignment operator, and a friend swap() function, which is marked as noexcept.

class CopyAndSwap
{
    public:
        CopyAndSwap() = default;
        virtual ~CopyAndSwap();                         // Virtual destructor

        CopyAndSwap(const CopyAndSwap& src);            // Copy constructor
        CopyAndSwap& operator=(const CopyAndSwap& rhs); // Assignment operator

        friend void swap(CopyAndSwap& first, CopyAndSwap& second) noexcept;

    private:
        // Private data members…
};

The implementation is as follows:

CopyAndSwap::~CopyAndSwap()
{
    // Implementation of destructor
}

CopyAndSwap::CopyAndSwap(const CopyAndSwap& src)
{
    // This copy constructor can first delegate to a non-copy constructor
    // if any resource allocations have to be done. See the Spreadsheet
    // implementation in Chapter 9 for an example.

    // Make a copy of all data members
}

void swap(CopyAndSwap& first, CopyAndSwap& second) noexcept
{
    using std::swap;  // Requires <utility>

    // Swap each data member, for example:
    // swap(first.mData, second.mData);
}

CopyAndSwap& CopyAndSwap::operator=(const CopyAndSwap& rhs)
{
    // Check for self-assignment
    if (this == &rhs) {
        return *this;
    }

    auto copy(rhs);     // Do all the work in a temporary instance
    swap(*this, copy);  // Commit the work with only non-throwing operations
    return *this;
}

Consult Chapter 9 for a more detailed discussion.

…Throw and Catch Exceptions

If you’ve been working on a team that doesn’t use exceptions (for shame!) or if you’ve gotten used to Java-style exceptions, the C++ syntax may escape you. Here’s a refresher that uses the built-in exception class std::runtime_error. In most large programs, you will write your own exception classes.

#include <stdexcept>
#include <iostream>

void throwIf(bool throwIt)
{
    if (throwIt) {
        throw std::runtime_error("Here's my exception");
    }
}

int main()
{
    try {
        throwIf(false); // doesn't throw
        throwIf(true);  // throws
    } catch (const std::runtime_error& e) {
        std::cerr << "Caught exception: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

Chapter 14 discusses exceptions in more detail.

…Read from a File

Complete details for file input are included in Chapter 13. Here is a quick sample program for file reading basics. This program reads its own source code and outputs it one token at a time:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream inputFile("FileRead.cpp");
    if (inputFile.fail()) {
        cerr << "Unable to open file for reading." << endl;
        return 1;
    }

    string nextToken;
    while (inputFile >> nextToken) {
        cout << "Token: " << nextToken << endl;
    }
    return 0;
}

…Write to a File

The following program outputs a message to a file, then reopens the file and appends another message. Additional details can be found in Chapter 13.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream outputFile("FileWrite.out");
    if (outputFile.fail()) {
        cerr << "Unable to open file for writing." << endl;
        return 1;
    }
    outputFile << "Hello!" << endl;
    outputFile.close();

    ofstream appendFile("FileWrite.out", ios_base::app);
    if (appendFile.fail()) {
        cerr << "Unable to open file for appending." << endl;
        return 2;
    }
    appendFile << "Append!" << endl;
    return 0;
}

…Write a Template Class

Template syntax is one of the messiest parts of the C++ language. The most-forgotten piece of the template puzzle is that code that uses a class template needs to be able to see the method implementations as well as the class template definition. The same holds for function templates. For class templates, the usual technique to accomplish this is to simply put the implementations directly in the header file following the class template definition, as in the following example. Another technique is to put the implementations in a separate file, often with an .inl extension, and then #include that file as the last line in the class template header file. The following program shows a class template that wraps a reference to an object and adds get and set semantics to it. Here is the SimpleTemplate.h header file:

template <typename T>
class SimpleTemplate
{
    public:
        SimpleTemplate(T& object);

        const T& get() const;
        void set(const T& object);
    private:
        T& mObject;
};

template<typename T>
SimpleTemplate<T>::SimpleTemplate(T& object) : mObject(object)
{
}

template<typename T>
const T& SimpleTemplate<T>::get() const
{
    return mObject;
}

template<typename T>
void SimpleTemplate<T>::set(const T& object)
{
    mObject = object;
}

The code can be tested as follows:

#include <iostream>
#include <string>
#include "SimpleTemplate.h"

using namespace std;

int main()
{
    // Try wrapping an integer.
    int i = 7;
    SimpleTemplate<int> intWrapper(i);
    i = 2;
    cout << "wrapped value is " << intWrapper.get() << endl;

    // Try wrapping a string.
    string str = "test";
    SimpleTemplate<string> stringWrapper(str);
    str += "!";
    cout << "wrapped value is " << stringWrapper.get() << endl;
    return 0;
}

Details about templates can be found in Chapters 12 and 22.

THERE MUST BE A BETTER WAY

As you read this paragraph, thousands of C++ programmers throughout the world are solving problems that have already been solved. Someone in a cubicle in San Jose is writing a smart pointer implementation from scratch that uses reference counting. A young programmer on a Mediterranean island is designing a class hierarchy that could benefit immensely from the use of mixin classes.

As a Professional C++ programmer, you need to spend less of your time reinventing the wheel, and more of your time adapting reusable concepts in new ways. This section gives some examples of general-purpose approaches that you can apply directly to your own programs or customize for your needs.

Resource Acquisition Is Initialization

RAII, or Resource Acquisition Is Initialization, is a simple yet very powerful concept. It is used to automatically free acquired resources when an RAII instance goes out of scope. This happens at a deterministic point in time. Basically, the constructor of a new RAII instance acquires ownership of a certain resource and initializes the instance with that resource, hence the name Resource Acquisition Is Initialization. The destructor automatically frees the acquired resource when the RAII instance is destroyed.

Here is an example of a File RAII class that safely wraps a C-style file handle (std::FILE) and automatically closes the file when the RAII instance goes out of scope. The RAII class also provides get(), release(), and reset() methods that behave similar to the same methods on certain Standard Library classes, such as std::unique_ptr.

#include <cstdio>

class File final
{
    public:
        File(std::FILE* file);
        ~File();

        // Prevent copy construction and copy assignment.
        File(const File& src) = delete;
        File& operator=(const File& rhs) = delete;

        // Allow move construction and move assignment.
        File(File&& src) noexcept = default;
        File& operator=(File&& rhs) noexcept = default;

        // get(), release(), and reset()
        std::FILE* get() const noexcept;
        std::FILE* release() noexcept;
        void reset(std::FILE* file = nullptr) noexcept;

    private:
        std::FILE* mFile;
};

File::File(std::FILE* file) : mFile(file)
{
}

File::~File()
{
    reset();
}

std::FILE* File::get() const noexcept
{
    return mFile;
}

std::FILE* File::release() noexcept
{
    std::FILE* file = mFile;
    mFile = nullptr;
    return file;
}

void File::reset(std::FILE* file /*= nullptr*/) noexcept
{
    if (mFile) {
        fclose(mFile);
    }
    mFile = file;
}

It can be used as follows:

File myFile(fopen("input.txt", "r"));

As soon as the myFile instance goes out of scope, its destructor is called, and the file is automatically closed.

I recommend to never include a default constructor or to explicitly delete the default constructor for RAII classes. The reason can best be explained using a Standard Library RAII class that has a default constructor, std::unique_lock (see Chapter 23). Proper use of unique_lock is as follows:

class Foo
{
    public:
        void setData();
    private:
        mutex mMutex;
};

void Foo::setData()
{
    unique_lock<mutex> lock(mMutex);
    // …
}

The setData() method uses the unique_lock RAII object to construct a local lock object that locks the mMutex data member and automatically unlocks that mutex at the end of the method.

However, because you do not directly use the lock variable after it has been defined, it is easy to make the following mistake:

void Foo::setData()
{
    unique_lock<mutex>(mMutex);
    // …
}

In this code, you accidentally forgot to give the unique_lock a name. This will compile, but it does not what you intended it to do! It will actually declare a local variable called mMutex (hiding the mMutex data member), and initialize it with a call to the unique_lock’s default constructor. The result is that the mMutex data member is not locked!

Double Dispatch

Double dispatch is a technique that adds an extra dimension to the concept of polymorphism. As described in Chapter 5, polymorphism lets the program determine behavior based on types at run time. For example, you could have an Animal class with a move() method. All Animals move, but they differ in terms of how they move. The move() method is defined for every derived class of Animal so that the appropriate method can be called, or dispatched, for the appropriate animal at run time without knowing the type of the animal at compile time. Chapter 10 explains how to use virtual methods to implement this run-time polymorphism.

Sometimes, however, you need a method to behave according to the run-time type of two objects, instead of just one. For example, suppose that you want to add a method to the Animal class that returns true if the animal eats another animal, and false otherwise. The decision is based on two factors: the type of animal doing the eating, and the type of animal being eaten. Unfortunately, C++ provides no language mechanism to choose a behavior based on the run-time type of more than one object. Virtual methods alone are insufficient for modeling this scenario because they determine a method, or behavior, depending on the run-time type of only the receiving object.

Some object-oriented languages provide the ability to choose a method at run time based on the run-time types of two or more objects. They call this feature multi-methods. In C++, however, there is no core language feature to support multi-methods, but you can use the double dispatch technique, which provides a way to make functions virtual for more than one object.

Attempt #1: Brute Force

The most straightforward way to implement a method whose behavior depends on the run-time types of two different objects is to take the perspective of one of the objects and use a series of if/else constructs to check the type of the other. For example, you could implement a method called eats() in each class derived from Animal that takes the other animal as a parameter. The method is declared pure virtual in the base class as follows:

class Animal
{
    public:
        virtual bool eats(const Animal& prey) const = 0;
};

Each derived class implements the eats() method, and returns the appropriate value based on the type of the parameter. The implementation of eats() for several derived classes follows. Note that the Dinosaur avoids the series of if/else constructs because—according to the author—dinosaurs eat anything:

bool Bear::eats(const Animal& prey) const
{
    if (typeid(prey) == typeid(Bear)) {
        return false;
    } else if (typeid(prey) == typeid(Fish)) {
        return true;
    } else if (typeid(prey) == typeid(Dinosaur)) {
        return false;
    }
    return false;
}

bool Fish::eats(const Animal& prey) const
{
    if (typeid(prey) == typeid(Bear)) {
        return false;
    } else if (typeid(prey) == typeid(Fish)) {
        return true;
    } else if (typeid(prey) == typeid(Dinosaur)) {
        return false;
    }
    return false;
}

bool Dinosaur::eats(const Animal& prey) const
{
    return true;
}

This brute force approach works, and it’s probably the most straightforward technique for a small number of classes. However, there are several reasons why you might want to avoid this approach:

  • Object-oriented programming (OOP) purists often frown upon explicitly querying the type of an object because it implies a design that is lacking a proper object-oriented structure.
  • As the number of types grows, such code can become messy and repetitive.
  • This approach does not force derived classes to consider new types. For example, if you added a Donkey, the Bear class would continue to compile, but would return false when told to eat a Donkey, even though everybody knows that bears eat donkeys.

Attempt #2: Single Polymorphism with Overloading

You could attempt to use polymorphism with overloading to circumvent all of the cascading if/else constructs. Instead of giving each class a single eats() method that takes an Animal reference, why not overload the method for each derived class of Animal? The base class definition would look like this:

class Animal
{
    public:
        virtual bool eats(const Bear&) const = 0;
        virtual bool eats(const Fish&) const = 0;
        virtual bool eats(const Dinosaur&) const = 0;
};

Because the methods are pure virtual in the base class, each derived class is forced to implement the behavior for every other type of Animal. For example, the Bear class contains the following methods:

class Bear : public Animal
{
    public:
        virtual bool eats(const Bear&) const override { return false; }
        virtual bool eats(const Fish&) const override { return true; }
        virtual bool eats(const Dinosaur&) const override { return false; }
};

This approach initially appears to work, but it really solves only half of the problem. In order to call the proper eats() method on an Animal, the compiler needs to know the compile-time type of the animal being eaten. A call such as the following will be successful because the compile-time types of both the animal that eats and the animal that is eaten are known:

Bear myBear;
Fish myFish;
cout << myBear.eats(myFish) << endl;

The missing piece is that the solution is only polymorphic in one direction. You can access myBear through an Animal reference and the correct method will be called:

Bear myBear;
Fish myFish;
Animal& animalRef = myBear;
cout << animalRef.eats(myFish) << endl;

However, the reverse is not true. If you pass an Animal reference to the eats() method, you will get a compilation error because there is no eats() method that takes an Animal. The compiler cannot determine, at compile time, which version to call. The following example does not compile:

Bear myBear;
Fish myFish;
Animal& animalRef = myFish;
cout << myBear.eats(animalRef) << endl; // BUG! No method Bear::eats(Animal&)

Because the compiler needs to know which overloaded version of the eats() method is going to be called at compile time, this solution is not truly polymorphic. It would not work, for example, if you were iterating over an array of Animal references and passing each one to a call to eats().

Attempt #3: Double Dispatch

The double dispatch technique is a truly polymorphic solution to the multiple-type problem. In C++, polymorphism is achieved by overriding methods in derived classes. At run time, methods are called based on the actual type of the object. The preceding single polymorphic attempt didn’t work because it attempted to use polymorphism to determine which overloaded version of a method to call instead of using it to determine on which class to call the method.

To begin, focus on a single derived class, perhaps the Bear class. The class needs a method with the following declaration:

virtual bool eats(const Animal& prey) const override;

The key to double dispatch is to determine the result based on a method call on the argument. Suppose that the Animal class has a method called eatenBy(), which takes an Animal reference as a parameter. This method returns true if the current Animal gets eaten by the one passed in. With such a method, the definition of eats() becomes very simple:

bool Bear::eats(const Animal& prey) const
{
    return prey.eatenBy(*this);
}

At first, it looks like this solution adds another layer of method calls to the single polymorphic method. After all, each derived class still has to implement a version of eatenBy() for every derived class of Animal. However, there is a key difference. Polymorphism is occurring twice! When you call the eats() method on an Animal, polymorphism determines whether you are calling Bear::eats(), Fish::eats(), or one of the others. When you call eatenBy(), polymorphism again determines which class’s version of the method to call. It calls eatenBy() on the run-time type of the prey object. Note that the run-time type of *this is always the same as the compile-time type so that the compiler can call the correct overloaded version of eatenBy() for the argument (in this case Bear).

Following are the class definitions for the Animal hierarchy using double dispatch. Note that forward class declarations are necessary because the base class uses references to the derived classes:

// forward declarations
class Fish;
class Bear;
class Dinosaur;

class Animal
{
    public:
        virtual bool eats(const Animal& prey) const = 0;

        virtual bool eatenBy(const Bear&) const = 0;
        virtual bool eatenBy(const Fish&) const = 0;
        virtual bool eatenBy(const Dinosaur&) const = 0;
};

class Bear : public Animal
{
    public:
        virtual bool eats(const Animal& prey) const override;

        virtual bool eatenBy(const Bear&) const override;
        virtual bool eatenBy(const Fish&) const override;
        virtual bool eatenBy(const Dinosaur&) const override;
};
// The definitions for the Fish and Dinosaur classes are identical to the
// Bear class, so they are not shown here.

The implementations follow. Note that each Animal-derived class implements the eats() method in the same way, but it cannot be factored up into the base class. The reason is that if you attempt to do so, the compiler won’t know which overloaded version of the eatenBy() method to call because *this would be an Animal, not a particular derived class. Method overload resolution is determined according to the compile-time type of the object, not its run-time type.

bool Bear::eats(const Animal& prey) const { return prey.eatenBy(*this); }
bool Bear::eatenBy(const Bear&) const { return false; }
bool Bear::eatenBy(const Fish&) const { return false; }
bool Bear::eatenBy(const Dinosaur&) const { return true; }

bool Fish::eats(const Animal& prey) const { return prey.eatenBy(*this); }
bool Fish::eatenBy(const Bear&) const { return true; }
bool Fish::eatenBy(const Fish&) const { return true; }
bool Fish::eatenBy(const Dinosaur&) const { return true; }

bool Dinosaur::eats(const Animal& prey) const { return prey.eatenBy(*this); }
bool Dinosaur::eatenBy(const Bear&) const { return false; }
bool Dinosaur::eatenBy(const Fish&) const { return false; }
bool Dinosaur::eatenBy(const Dinosaur&) const { return true; }

Double dispatch is a concept that takes a bit of getting used to. I suggest playing with this code to adapt to the concept and its implementation.

Mixin Classes

Chapters 5 and 10 introduce the technique of using multiple inheritance to build mixin classes. Mixin classes add a small piece of extra behavior to a class in an existing hierarchy. You can usually spot a mixin class by its name, which ends in “-able”, for example, Clickable, Drawable, Printable, or Lovable.

Designing a Mixin Class

Mixin classes contain actual code that can be reused by other classes. A single mixin class implements a well-defined piece of functionality. For example, you might have a mixin class called Playable that is mixed into certain types of media objects. The mixin class could, for example, contain most of the code to communicate with the computer’s sound drivers. By mixing in the class, the media object would get that functionality for free.

When designing a mixin class, you need to consider what behavior you are adding and whether it belongs in the object hierarchy or in a separate class. Using the previous example, if all media classes are playable, the base class should derive from Playable instead of mixing the Playable class into all of the derived classes. If only certain media classes are playable and they are scattered throughout the hierarchy, a mixin class makes sense.

One of the cases where mixin classes are particularly useful is when you have classes organized into a hierarchy on one axis, but they also contain similarities on another axis. For example, consider a war simulation game played on a grid. Each grid location can contain an Item with attack and defense capabilities and other characteristics. Some items, such as a Castle, are stationary. Others, such as a Knight or FloatingCastle, can move throughout the grid. When initially designing the object hierarchy, you might end up with something like Figure 28-1, which organizes the classes according to their attack and defense capabilities.

c28-fig-0001

FIGURE 28-1

The hierarchy in Figure 28-1 ignores the movement functionality that certain classes contain. Building your hierarchy around movement would result in a structure similar to Figure 28-2.

c28-fig-0002

FIGURE 28-2

Of course, the design of Figure 28-2 throws away all the organization of Figure 28-1. What’s a good object-oriented programmer to do?

There are two common solutions for this problem. Assuming that you go with the first hierarchy, organized around attackers and defenders, you need some way to work movement into the equation. One possibility is that, even though only a portion of the derived classes support movement, you could add a move() method to the Item base class. The default implementation would do nothing. Certain derived classes would override move() to actually change their location on the grid.

The other approach is to write a Movable mixin class. The elegant hierarchy from Figure 28-1 could be preserved, but certain classes in the hierarchy would derive from Movable in addition to their parent. Figure 28-3 shows this design.

c28-fig-0003

FIGURE 28-3

Implementing a Mixin Class

Writing a mixin class is no different from writing a normal class. In fact, it’s usually much simpler. Using the earlier war simulation, the Movable mixin class might look as follows:

class Movable
{
    public:
        virtual void move() { /* Implementation to move an item… */ }
};

This Movable mixin class implements the actual code to move an item on the grid. It also provides a type for Items that can be moved. This allows you to create, for example, an array of all movable items without knowing or caring what actual derived class of Item they belong to.

Using a Mixin Class

The code for using a mixin class is syntactically equivalent to multiple inheritance. In addition to deriving from your parent class in the main hierarchy, you also derive from the mixin class:

class FloatingCastle : public Castle, public Movable
{
    // …
};

This mixes in the functionality provided by the Movable mixin class into the FloatingCastle class. Now you have a class that exists in the most logical place in the hierarchy, but still shares commonality with objects elsewhere in the hierarchy.

OBJECT-ORIENTED FRAMEWORKS

When graphical operating systems first came on the scene in the 1980s, procedural programming was the norm. At the time, writing a GUI application usually involved manipulating complex data structures and passing them to OS-provided functions. For example, to draw a rectangle in a window, you might have had to populate a Window struct with the appropriate information and pass it to a drawRect() function.

As object-oriented programming (OOP) grew in popularity, programmers looked for a way to apply the OOP paradigm to GUI development. The result is known as an object-oriented framework. In general, a framework is a set of classes that are used collectively to provide an object-oriented interface to some underlying functionality. When talking about frameworks, programmers are usually referring to large class libraries that are used for general application development. However, a framework can really represent functionality of any size. If you write a suite of classes that provides database functionality for your application, those classes could be considered a framework.

Working with Frameworks

The defining characteristic of a framework is that it provides its own set of techniques and patterns. Frameworks usually require a bit of learning to get started with because they have their own mental model. Before you can work with a large application framework, such as the Microsoft Foundation Classes (MFC), you need to understand its view of the world.

Frameworks vary greatly in their abstract ideas and in their actual implementation. Many frameworks are built on top of legacy procedural APIs, which may affect various aspects of their design. Other frameworks are written from the ground up with object-oriented design in mind. Some frameworks might ideologically oppose certain aspects of the C++ language. For example, a framework could consciously shun the notion of multiple inheritance.

When you start working with a new framework, your first task is to find out what makes it tick. To what design principles does it subscribe? What mental model are its developers trying to convey? What aspects of the language does it use extensively? These are all vital questions, even though they may sound like things that you’ll pick up along the way. If you fail to understand the design, model, or language features of the framework, you will quickly get into situations where you overstep the bounds of the framework.

An understanding of the framework’s design will also make it possible for you to extend it. For example, if the framework omits a feature, such as support for printing, you could write your own printing classes using the same model as the framework. By doing so, you retain a consistent model for your application, and you have code that can be reused by other applications.

A framework might use certain specific data types. For example, the MFC framework uses the CString data type to represent strings, instead of using the Standard Library std::string class. This does not mean that you have to switch to the data types provided by the framework for your entire code base. Instead, you should convert the data types on the boundaries between the framework code and the rest of your code.

The Model-View-Controller Paradigm

As I mentioned earlier, frameworks vary in their approaches to object-oriented design. One common paradigm is known as model-view-controller, or MVC. This paradigm models the notion that many applications commonly deal with a set of data, one or more views on that data, and manipulation of the data.

In MVC, a set of data is called the model. In a race car simulator, the model would keep track of various statistics, such as the current speed of the car and the amount of damage it has sustained. In practice, the model often takes the form of a class with many getters and setters. The class definition for the model of the race car might look as follows:

class RaceCar
{
    public:
        RaceCar();
        virtual ~RaceCar() = default;

        virtual double getSpeed() const;
        virtual void setSpeed(double speed);

        virtual double getDamageLevel() const;
        virtual void setDamageLevel(double damage);
    private:
        double mSpeed;
        double mDamageLevel;
};

A view is a particular visualization of the model. For example, there could be two views on a RaceCar. The first view could be a graphical view of the car, and the second could be a graph that shows the level of damage over time. The important point is that both views are operating on the same data—they are different ways of looking at the same information. This is one of the main advantages of the MVC paradigm: by keeping data separated from its display, you can keep your code more organized, and easily create additional views.

The final piece to the MVC paradigm is the controller. The controller is the piece of code that changes the model in response to some event. For example, when the driver of the race car simulator runs into a concrete barrier, the controller instructs the model to bump up the car’s damage level and reduce its speed. The controller can also manipulate the view. For example, when the user scrolls a scrollbar in the user interface, the controller instructs the view to scroll its content.

The three components of MVC interact in a feedback loop. Actions are handled by the controller, which adjusts the model and/or views. If the model changes, it notifies the views to update them. This interaction is shown in Figure 28-4.

c28-fig-0004

FIGURE 28-4

The model-view-controller paradigm has gained widespread support within many popular frameworks. Even nontraditional applications, such as web applications, are moving in the direction of MVC because it enforces a clear separation between data, the manipulation of data, and the displaying of data.

The MVC pattern has evolved into several different variants, such as model-view-presenter (MVP), model-view-adapter (MVA), model-view-viewmodel (MVVM), and so on.

SUMMARY

In this chapter, you read about some of the common techniques that Professional C++ programmers use consistently in their projects. As you advance as a software developer, you will undoubtedly form your own collection of reusable classes and libraries. Discovering design techniques opens the door to developing and using patterns, which are higher-level reusable constructs. You will experience the many applications of patterns next in Chapter 29.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset