Policy-Based Component Design
It's difficult to predict the exact needs of a client when building reusable software components. Sometimes even your own needs change drastically over the course of a project. One useful technique to deal with the variability is policy-based component design.
The idea is to build a component that implements a core behaviour and applies a client-specified policy to make the key decisions. For example, if I built a hash table component, the client should be able to specify when and how to resize the table. Some clients may double the size of their hash table when the load factor reaches 0.8 whereas others may increase the table size to some fixed value based on expected data growth once they have a good estimate of it. It all depends on the nature of the environment in which the component is used. And only the client knows that.
There are many ways to implement a policy-based design. In Java, I could use the strategy pattern. In C, I would use function pointers and a context (e.g. void pointer). Andrei Alexandrescu used C++ templates to achieve this goal in Modern C++ Design. All of those approaches are perfectly valid and result in more reusable components.
A final note: policy-based design applies to components at any granularity, not just at the class/function level. PAM is a fine example of a coarse-grained policy-based component which I mentioned in a previous post. Or consider a hypervisor that manages physical resource allocation based on a user's needs (e.g. allocate 512MB of RAM to virtual machine 1).
Image from Amazon
The idea is to build a component that implements a core behaviour and applies a client-specified policy to make the key decisions. For example, if I built a hash table component, the client should be able to specify when and how to resize the table. Some clients may double the size of their hash table when the load factor reaches 0.8 whereas others may increase the table size to some fixed value based on expected data growth once they have a good estimate of it. It all depends on the nature of the environment in which the component is used. And only the client knows that.
There are many ways to implement a policy-based design. In Java, I could use the strategy pattern. In C, I would use function pointers and a context (e.g. void pointer). Andrei Alexandrescu used C++ templates to achieve this goal in Modern C++ Design. All of those approaches are perfectly valid and result in more reusable components.
A final note: policy-based design applies to components at any granularity, not just at the class/function level. PAM is a fine example of a coarse-grained policy-based component which I mentioned in a previous post. Or consider a hypervisor that manages physical resource allocation based on a user's needs (e.g. allocate 512MB of RAM to virtual machine 1).
Image from Amazon