Chapter 28

Incorporating Design Techniques and Frameworks

WHAT’S IN THIS CHAPTER?

  • An overview of C++ language features that are common but involve easy-to-forget syntax
  • What the double dispatch technique is and how to use it
  • How to use mix-in classes
  • What frameworks are

One of the major themes of this book has been the adoption of reusable techniques and patterns. As a programmer, you tend to face similar problems repeatedly. With an arsenal of diverse approaches, you can save yourself time by applying the proper technique to a given problem.

A design technique is a standard approach for solving a particular problem in C++. Often, a design technique aims to overcome an annoying feature or language deficiency. Other times, a design technique is a piece of code that you use in many different programs to solve a common C++ problem.

This chapter focuses on design techniques — C++ idioms that aren’t necessarily built-in parts of the language, but are nonetheless frequently used. The first part of this chapter covers the language features in C++ that are common but involve easy-to-forget syntax. Most of this material is a review, but it is a useful reference tool when the syntax escapes you. The topics covered include:

  • Starting a class from scratch
  • Extending a class with a subclass
  • Throwing and catching exceptions
  • Reading from a file
  • Writing to a file
  • Defining a template class

The second part of this chapter focuses on higher-level techniques that build upon C++ language features. These techniques offer a better way to accomplish everyday programming tasks. Topics include:

  • The double dispatch technique
  • Mix-in classes

This chapter concludes with an introduction to frameworks, a coding technique that greatly eases the development of large applications.

“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 the authors of this book need to look things up. 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 forget the syntax, turn to these pages for a refresher.

... Write a Class

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

image
#ifndef _simple_h_
#define _simple_h_
// A simple class that illustrates class definition syntax.
class Simple 
{
    public:
        Simple();                       // Constructor
        virtual ~Simple();              // Destructor
        virtual void publicMethod();    // Public method
        int mPublicInteger;             // Public data member
    protected:
        int mProtectedInteger;          // Protected data member
        static const int mConstant = 2; // Protected constant
        static int sStaticInt;          // Protected static data member
    private:
        int mPrivateInteger;            // Private data member
        // Disallow assignment and pass-by-value
        Simple(const Simple& src);
        Simple& operator=(const Simple& rhs);
};
#endif

Code snippet from SimpleSimple.h

Note that this class definition shows what is possible. However, in your own class definitions, you should try to avoid having public data members. Instead, you should make them protected and provide public getter and setter methods. You should also try to minimize private data members, and instead opt for protected data members so that you don’t prevent subclasses from using them. You can make the copy constructor and assignment operator private to prevent assignment and pass-by-value.

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

image
#include "Simple.h"
int Simple::sStaticInt = 0;   // Initialize static data member.
Simple::Simple()
{
    // Implementation of constructor
}
Simple::~Simple()
{
   // Implementation of destructor
}
void Simple::publicMethod()
{
    // Implementation of public method
}

Code snippet from SimpleSimple.cpp

Note that with C++11, you can initialize sStaticInt within the class definition as explained in Chapter 6.

Chapters 6 and 7 provide all the details for writing your own classes.

... Subclass an Existing Class

To subclass, you declare a new class that is a public extension of another class. Here is the definition for a sample subclass called SubSimple:

image
#ifndef _subsimple_h_
#define _subsimple_h_
#include "Simple.h"
// A subclass of the Simple class
class SubSimple : public Simple
{
    public:
        SubSimple();                  // Constructor
        virtual ~SubSimple();         // Destructor
        virtual void publicMethod();  // Overridden method
        virtual void anotherMethod(); // Added method
};
#endif

Code snippet from SimpleSubSimple.h

The implementation:

image
#include "SubSimple.h"
SubSimple::SubSimple() : Simple()
{
    // Implementation of constructor
}
SubSimple::~SubSimple()
{
    // Implementation of destructor
}
void SubSimple::publicMethod()
{
    // Implementation of overridden method
}
void SubSimple::anotherMethod()
{
    // Implementation of added method
}

Code snippet from SimpleSubSimple.cpp

Consult Chapter 8 for details on inheritance techniques.

... 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, which uses the built-in exception class std::runtime_error. In most large programs, you will write your own exception classes.

image
#include <stdexcept>
#include <iostream>
void throwIf(bool inShouldThrow) throw (std::runtime_error)
{
    if (inShouldThrow) {
        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 0;
}

Code snippet from ExceptionsExceptions.cpp

Chapter 10 discusses exceptions in more detail.

... Read from a File

Complete details for file input are included in Chapter 15. 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.

image
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    ifstream inFile("FileRead.cpp");
    if (inFile.fail()) {
        cerr << "Unable to open file for reading." << endl;
        return 1;
    }
    string nextToken;
    while (inFile >> nextToken) {
        cout << "Token: " << nextToken << endl;
    }
    inFile.close();
    return 0;
}

Code snippet from FileReadFileRead.cpp

... 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 15.

image
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ofstream outFile("FileWrite.out");
    if (outFile.fail()) {
        cerr << "Unable to open file for writing." << endl;
        return 1;
    }
    outFile << "Hello!" << endl;
    outFile.close();
 
    ofstream appendFile("FileWrite.out", ios_base::app);
    if (appendFile.fail()) {
        cerr << "Unable to open file for appending." << endl;
        return 2;
    }
    appendFile << "Append!" << endl;
    appendFile.close();
    return 0;
}

Code snippet from FileWriteFileWrite.cpp

... 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 the template needs to be able to see the method implementations as well as the class template definition. The usual technique to accomplish this is to #include the source file in the header file so that clients can #include the header file as they normally do. The following program shows a class template that wraps a reference to an object and adds get and set semantics to it.

image
template <typename T>
class SimpleTemplate
{
    public:
        SimpleTemplate(T& inObject);
        const T& get() const;
        void set(T& inObject);
    protected:
        T& mObject;
};
#include "SimpleTemplate.cpp" // Include the implementation!

Code snippet from TemplateSimpleTemplate.h

image
template<typename T>
SimpleTemplate<T>::SimpleTemplate(T& inObject) : mObject(inObject)
{
}
template<typename T>
const T& SimpleTemplate<T>::get() const
{
    return mObject;
}
template<typename T>
void SimpleTemplate<T>::set(T& inObject)
{
    mObject = inObject;
}

Code snippet from TemplateSimpleTemplate.cpp

image
#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 << "wrapper value is " << intWrapper.get() << endl;
 
    // Try wrapping a string.
    string str = "test";
    SimpleTemplate<string> stringWrapper(str);
    str += "!";
    cout << "wrapper value is " << stringWrapper.get() << endl;
    return 0;
}

Code snippet from TemplateTemplateTest.cpp

Details about templates can be found in Chapters 19 and 20.

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 mix-in 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. The following techniques are general-purpose approaches that you can apply directly to your own programs or customize for your needs.

Double Dispatch

Double dispatch is a technique that adds an extra dimension to the concept of polymorphism. As described in Chapter 3, polymorphism lets the program determine behavior based on run-time types. 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 subclass 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 8 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 technique to make functions virtual for more than one object.

pen.gif

Double dispatch is really a special case of multiple dispatch, in which a behavior is chosen depending on the run-time types of two or more objects. In practice, double dispatch, which chooses a behavior based on the run-time types of exactly two objects, is usually sufficient.

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() on each Animal subclass that takes the other animal as an argument. The method would be declared pure virtual in the base class as follows:

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

Code snippet from DoubleDispatchDoubleDispatchBruteForce.cpp

Each subclass would implement the eats() method and return the appropriate value based on the type of the argument. The implementation of eats() for several subclasses follows. Note that the Dinosaur subclass avoids the series of if/else constructs because (according to the authors) dinosaurs eat anything.

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

Code snippet from DoubleDispatchDoubleDispatchBruteForce.cpp

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 such an approach:

  • OOP purists often frown upon explicitly querying the type of an object because it implies a design that is lacking in proper object-oriented structure.
  • As the number of types grows, such code can grow messy and repetitive.
  • This approach does not force subclasses to consider new types. For example, if you added a Donkey subclass, 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 Animal subclass? The base class definition would look like this:

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

Because the methods are pure virtual in the superclass, each subclass would be forced to implement the behavior for every other type of Animal. For example, the Bear class would contain the following methods:

class Bear : public Animal
{
    public:
        virtual bool eats(const Bear& inPrey) const { return false; }
        virtual bool eats(const Fish& inPrey) const { return true; }
        virtual bool eats(const Dinosaur& inPrey) const { 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 eater and the eaten animals 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 could access myBear in the context of an Animal and the correct method would be called:

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

However, the reverse is not true. If you accessed myFish in the context of the Animal class and passed that to the eats() method, you would get a compile 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 will 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 subclasses. 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 subclass, perhaps the Bear class. The class needs a method with the following declaration:

virtual bool eats(const Animal& inPrey) const;

The key to double dispatch is to determine the result based on a method call on the argument. Suppose that the Animal class had a method called eatenBy(), which took an Animal reference as a parameter. This method would return 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& inPrey) const 
{
    return inPrey.eatenBy(*this);
}

At first, it looks like this solution adds another layer of method calls to the single polymorphic method. After all, each subclass will still have to implement a version of eatenBy() for every subclass 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 inPrey 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 subclasses.

image
// forward declarations
class Fish;
class Bear;
class Dinosaur;
class Animal
{
    public:
        virtual bool eats(const Animal& inPrey) const = 0;
        virtual bool eatenBy(const Bear& inBear) const = 0;
        virtual bool eatenBy(const Fish& inFish) const = 0;
        virtual bool eatenBy(const Dinosaur& inDinosaur) const = 0;
};
class Bear : public Animal
{
    public:
        virtual bool eats(const Animal& inPrey) const;
        virtual bool eatenBy(const Bear& inBear) const;
        virtual bool eatenBy(const Fish& inFish) const;
        virtual bool eatenBy(const Dinosaur& inDinosaur) const;
};
class Fish : public Animal
{
    public:
        virtual bool eats(const Animal& inPrey) const;
        virtual bool eatenBy(const Bear& inBear) const;
        virtual bool eatenBy(const Fish& inFish) const;
        virtual bool eatenBy(const Dinosaur& inDinosaur) const;
};
class Dinosaur : public Animal
{
    public:
        virtual bool eats(const Animal& inPrey) const;
        virtual bool eatenBy(const Bear& inBear) const;
        virtual bool eatenBy(const Fish& inFish) const;
        virtual bool eatenBy(const Dinosaur& inDinosaur) const;
};

Code snippet from DoubleDispatchDoubleDispatch.cpp

The implementations follow. Note that each Animal subclass implements the eats() method in the same way, but it cannot be factored up into the parent 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 subclass. Method overload resolution is determined according to the compile-time type of the object, not its run-time type.

image
bool Bear::eats(const Animal& inPrey) const 
{
    return inPrey.eatenBy(*this);
}
bool Bear::eatenBy(const Bear& inBear) const 
{ 
    return false; 
}
bool Bear::eatenBy(const Fish& inFish) const 
{ 
    return false; 
}
bool Bear::eatenBy(const Dinosaur& inDinosaur) const 
{ 
    return true;
}
 
bool Fish::eats(const Animal& inPrey) const 
{
    return inPrey.eatenBy(*this);
}
bool Fish::eatenBy(const Bear& inBear) const 
{ 
    return true; 
}
bool Fish::eatenBy(const Fish& inFish) const 
{ 
    return true; 
}
bool Fish::eatenBy(const Dinosaur& inDinosaur) const 
{ 
    return true;
}
 
bool Dinosaur::eats(const Animal& inPrey) const 
{
    return inPrey.eatenBy(*this);
}
bool Dinosaur::eatenBy(const Bear& inBear) const 
{ 
    return false; 
}
bool Dinosaur::eatenBy(const Fish& inFish) const 
{ 
    return false; 
}
bool Dinosaur::eatenBy(const Dinosaur& inDinosaur) const 
{ 
    return true;
}

Code snippet from DoubleDispatchDoubleDispatch.cpp

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

Mix-In Classes

Chapters 3 and 8 introduce the technique of using multiple inheritance to build mix-in classes. Mix-in classes add a small piece of extra behavior to a class in an existing hierarchy. You can usually spot a mix-in class by its name ending in “-able”, such as Clickable, Drawable, Printable, or Lovable.

Designing a Mix-In Class

Mix-in classes come in several forms. Because mix-in classes are not a formal language feature, you can write them however you want without breaking any rules. Some mix-in classes indicate that a class supports a certain behavior, such as a hypothetical Drawable mix-in class. Any class that mixes in the Drawable class must implement the method draw(). The mix-in class itself contains no functionality — it just marks an object as supporting the draw() behavior. This usage is similar to Java’s notion of an interface — a list of prescribed behaviors without their implementation.

Other mix-in classes contain actual code. You might have a mix-in class called Playable that is mixed into certain types of media objects. The mix-in 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 mix-in 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 descend from Playable instead of mixing the Playable class into all of the subclasses. If only certain media classes are playable and they are scattered throughout the hierarchy, a mix-in class makes sense.

One of the cases where mix-in classes are particularly useful is when you have classes organized into a hierarchy on one axis, but they also contain similarity 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.

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.

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 subclasses support movement, you could add a move() method to the Item base class. The default implementation would do nothing. Certain subclasses would override move() to actually change their location on the grid.

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

Implementing a Mix-In Class

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

class Movable
{
    public:
        virtual void move() = 0;
};

This Movable mix-in class doesn’t contain any actual functionality. However, it does two very important things. First, it 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 subclass of Item they belong to. The Movable class also declares that all movable items must implement a method called move(). This way, you could iterate over all of the Movable objects and tell each of them to move.

Using a Mix-In Class

The code for using a mix-in class is syntactically equivalent to multiple inheritance. In addition to subclassing your parent class in the main hierarchy, you also subclass the mix-in class:

class FloatingCastle : public Castle, public Movable
{
    public:
        virtual void move();
    // Other methods and members not shown here
};

The only remaining task is to provide a definition of the move() method for FloatingCastle. Once that is done, you’ll 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 populate a Window struct with the appropriate information and pass it to a drawRect() function.

As object-oriented programming grew in popularity, programmers looked for a way to apply the OO 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, such as the BeOS framework, which consciously shunned 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. For example, if the framework has its own string class, e.g., MFC’s CString, and you choose to use another string class, e.g., std::string, you will end up with a lot of unnecessary conversion work that could have been easily avoided.

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.

The Model-View-Controller Paradigm

As mentioned, 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();
        int getSpeed() const;
        void setSpeed(int inValue);
        int getDamageLevel() const;
        void setDamageLevel(int inValue);
    protected:
        int mSpeed;
        int 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 would instruct the model to bump up the car’s damage level and reduce its speed.

The three components of MVC interact in a feedback loop. Actions are handled by the controller, which adjusts the model, resulting in a change to the view(s). This interaction is shown in 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.

SUMMARY

In this chapter, you have 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