Policy-based design, also known as policy-based class design or policy-based programming, is a computer programming paradigm based on an idiom for C++ known as policies. A programming paradigm is a fundamental style of Computer programming. An idiom is a Phrase whose meaning cannot be deduced from the literal Definition, but refers instead to a figurative meaning that is known only C++ (" C Plus Plus " ˌsiːˌplʌsˈplʌs is a general-purpose Programming language. It has been described as a compile-time variant of the strategy pattern, and has connections with C++ template metaprogramming. In Computer science, compile time refers to either the operations performed by a Compiler (the "compile-time operations" or Programming language In Computer programming, the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby Algorithms can Template metaprogramming is a Metaprogramming technique in which templates are used by a Compiler to generate temporary source code which is merged by It was first popularized by Andrei Alexandrescu with his 2001 book Modern C++ Design and his column Generic<Programming> in the C/C++ Users Journal. Andrei Alexandrescu is widely regarded as one of the foremost experts on advanced C++ programming Modern C++ Design is a book written by Andrei Alexandrescu, published in 2001 and subtitled "Generic Programming and Design Patterns Applied" C/C++ Users Journal was a computer magazine / Journal published by CMP Media LLC in the United States.
Although the technique could theoretically be applied to other languages, it is currently closely associated with C++, and depends on the particular feature set of that language. Furthermore, even in C++ it requires a compiler with highly robust support for templates, which wasn't common before about 2003. A compiler is a Computer program (or set of programs that translates text written in a computer language (the source language) into another Robustness is the quality of being able to withstand stresses pressures or changes in procedure or circumstance Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types.
Contents |
The central idiom in policy-based design is a class template (called the host class), taking several type parameters as input, which are instantiated with types selected by the user (called policy classes), each implementing a particular implicit interface (called a policy), and encapsulating some orthogonal (or mostly orthogonal) aspect of the behavior of the instantiated host class. In Object-oriented programming, a class is a Programming language construct that is used as a blueprint to create objects This blueprint includes attributes A data type in Programming languages is an attribute of a datum which tells the computer (and the programmer something about the kind of datum it is In Computer programming, a parameter is a variable which takes on the meaning of a corresponding Argument (computer science is same article--> argument In its simplest embodiment an object is an allocated region of storage Implementation is the realization of an application or execution of a Plan, idea Model, Design, Specification, standard, Algorithm Interface generally refers to an abstraction that an entity provides of itself to the outside In Computer science, separation of concerns ( SoC) is the process of breaking a Computer program into distinct features that overlap in functionality as In Mathematics, two Vectors are orthogonal if they are Perpendicular, i By supplying a host class combined with a set of different, canned implementations for each policy, a library or module can support an exponential number of different behavior combinations, resolved at compile time, and selected by mixing and matching the different supplied policy classes in the instantiation of the host class template. In Computer science, a library is a collection of Subroutines used to develop Software. Modular programming is a software design technique that increases the extent to which software is composed from separate parts called modules Exponential growth (including Exponential decay) occurs when the growth rate of a mathematical function is proportional to the function's current value Additionally, by writing a custom implementation of a given policy, a policy-based library can be used in situations requiring behaviors unforeseen by the library implementor. Even in cases where no more than one implementation of each policy will ever be used, decomposing a class into policies can aid the design process, by increasing modularity and highlighting exactly where orthogonal design decisions have been made.
While assembling software components out of interchangeable modules, communicating with each other through generic interfaces, is far from a new concept, policy-based design represents an innovation in the way it applies that concept at the (relatively low) level of defining the behavior of an individual class.
Policy classes have some similarity to callbacks, but differ in that, rather than consisting of a single function, a policy class will typically contain several related functions (methods), often combined with state variables and/or other facilities such as nested types. In Computer programming, a callback is Executable code that is passed as an argument to other code In Computer science, a subroutine ( function, method, procedure, or subprogram) is a portion of code within a larger In Object-oriented programming, the term method refers to a Subroutine that is exclusively associated either with a class (called class methods In Computer science and Automata theory, a state is a unique configuration of information in a program or machine A variable (ˈvɛərɪəbl is an Attribute of a physical or an abstract System which may change its Value while it is under Observation.
A policy-based host class can be thought of as a type of metafunction, taking a set of behaviors represented by types as input, and returning as output a type representing the result of combining those behaviors into a functioning whole. Template metaprogramming is a Metaprogramming technique in which templates are used by a Compiler to generate temporary source code which is merged by (Unlike MPL metafunctions, however, the output is usually represented by the instantiated host class itself, rather than a nested output type. The Boost C++ Libraries are a collection of Peer-reviewed Open source libraries that extend the functionality of C++. )
A key feature of the policy idiom is that, usually (though it is not strictly necessary), the host class will derive from (make itself a child class of) each of its policy classes using multiple inheritance. In Object-oriented programming, inheritance is a way to form new classes (instances of which are called objects using classes that have already been defined In Object-oriented programming, a subclass is a class that inherits some properties from its superclass. Multiple inheritance refers to a feature of some object-oriented Programming languages in which a class can inherit behaviors and features from (An alternative is for the host class to merely contain a member variable of each policy class type; however the former approach has the major advantage that a policy class can add new methods, inherited by the instantiated host class and accessible to its users, which the host class itself need not even know about. ) A notable feature of this aspect of the policy idiom is that, relative to object-oriented programming, policies invert the relationship between base class and derived class - whereas in OOP interfaces are traditionally represented by (abstract) base classes and implementations of interfaces by derived classes, in policy-based design the derived (host) class represents the interfaces and the base (policy) classes implement them. Object-oriented programming (OOP is a Programming paradigm that uses " objects " and their interactions to design applications and computer programs In Computer science, a superclass is a class from which other classes are derived In Object-oriented programming, a virtual function or virtual method is one whose behavior is defined within an inheriting class by a function with the same signature It should also be noted that in the case of policies, the class inheritance does not represent an "is a" relationship between the host and the policy classes. While this would traditionally be considered evidence of a design defect in OOP contexts, this doesn't apply in the context of the policy idiom.
A disadvantage of policies in their current incarnation is that the policy interface doesn't have a direct, explicit representation in code, but rather is defined implicitly, via duck typing, and must be documented separately and manually, in comments. In Computer science, source code (commonly just source or code) is any sequence of statements or declarations written in some Human-readable In Computer programming, duck typing is a style of Dynamic typing in which an object's current set of methods and properties determines the valid In Computer programming, a comment is a Programming language construct used to embed Information in the Source code of a computer program This limitation will, however, be addressed by the type concepts feature proposed for the forthcoming version of the ISO C++ standard, known as C++0x. In Generic programming, a concept is a description of supported operations on a type including syntax and semantics ISO / IEC International Standard 14882 Programming Languages &mdash C++, is the official standard for the C++ programming language and library defined C++0x is the planned new standard for the C++ programming language.
The main idea is to use commonality-variability analysis to divide the type into the fixed implementation and interface, the policy-based class, and the different policies. The trick is to know what goes into the main class, and what policies should one create. Andrei's excellent article, mentioned above, gives us the clue: wherever we would need to make a possible limiting design decision, we should postpone that decision, we should delegate it to an appropriately named policy.
Policy classes can contain implementation, type definitions and so forth. Basically, the designer of the main template class will define what the policy classes should provide, what customization points they need to implement.
As we go by the analysis in policy-based design, it is a delicate task to create a good set of policies, just the right number. As little as necessary, but not less. The different customization points, which belong together, should go into one policy argument, such as storage policy, validation policy and so forth. A good rule of thumb during design is that you should be able to give a name to your policy, which represents a concept, and not one which represent an operation or some really tiny implementation detail. Persistence policy seems to be a good choice, while how to save policy does not.
As you do your policy-based design you will see how many other techniques will be useful, even if changed a bit, during your work. One example is that the template method pattern can be reinterpreted for compile time; so that your main class has a skeleton algorithm, which — at customization points — calls the appropriate functions of some of the policies. In Software engineering, the template method pattern is a design pattern. Skeleton programming is a style of Computer programming based on simple high-level program structures and Dummy code. You will also find yourself in using your policy classes as traits are used, asking type information, delegating type related tasks to it, a storage policy is one example where it can happen.
Presented below is a simple (contrived) example of a C++ hello world program, where the text to be printed and the method of printing it are decomposed using policies. A "Hello World" program is a Computer program that prints out "Hello world!" on a Display device.
template< typename output_policy, typename language_policy > class HelloWorld : public output_policy, public language_policy { using output_policy::Print; using language_policy::Message; public: //behaviour method void Run() { //two policy methods Print( Message() ); } }; #include <iostream> class HelloWorld_OutputPolicy_WriteToCout { protected: template< typename message_type > void Print( message_type message ) { std::cout << message << std::endl; } }; #include <string> class HelloWorld_LanguagePolicy_English { protected: std::string Message() { return "Hello, World!"; } }; class HelloWorld_LanguagePolicy_German{ protected: std::string Message() { return "Hallo Welt!"; } }; int main() { /* example 1 */ typedef HelloWorld< HelloWorld_OutputPolicy_WriteToCout, HelloWorld_LanguagePolicy_English > my_hello_world_type; my_hello_world_type hello_world; hello_world. Run(); //returns Hello World! /* example 2 * does the same but uses another policy, the language has changed */ typedef HelloWorld< HelloWorld_OutputPolicy_WriteToCout, HelloWorld_LanguagePolicy_German > my_other_hello_world_type; my_other_hello_world_type hello_world2; hello_world2. Run(); //returns Hallo Welt! }
You could easily write another Output policy by adding a new class with the member function print() and take that as the new outputpolicy.