Imagine an application based on options.
I want to add an exclamation mark to the end of every string (itself, an extremely easy task). However, I have an option in web.config or an XML file, so if the option is true, the exclamation is appended, otherwise it isn’t.
I know how to check web.config or an xml file for the setting’s value, however, what is the best way to do this? In the case of a string, it will be heavily used in any program.
I could write:
if (ExclamationIsSet)
{
// Append here
}
// Otherwise it isn't set, so don't.
However, this isn’t practical for a large (or even small) codebase. Is there a way to get rid of this manual checking? I’ve heard AOP or attributes may be able to solve this, but I haven’t seen an example.
What methods could solve this problem?
The operation can be described as:
This encapsulates the how (Web.config, XML, etc.) and emphasizes the what (decorating a string).
Then, any class which might need to decorate text can take an instance of that interface:
Example implementations of
ITextDecoratormight be:An example usage of these classes might be:
Notice the decoupling of the exclamation point appending from its conditional invocation. Both classes can now be reused independent of the other. This design style of fine-grained objects works best with an Inversion of Control (IoC) container. However, it is not required.