Is there a pattern for adding "options" to a class?

configuration, design-patterns

Solution

How about the Decorator pattern? It's designed for dynamically adding behavior to a class.

Problem

I have a class on which I want to allow several (~20+) configuration options. Each option turns on or off a piece of functionality, or otherwise alters operations. To facilitate this, I coded a separate options class with default values. However, I had to litter my code with guard conditions to determine how methods should behave. I am almost done, but now the code seems to smell. Is there a preferred method/pattern to implement a class like this? EDIT: More specifically, I am working on a parsing class. Each option configures mutually exclusive portions of the basic parsing algorithm. For example I have several areas in my class that look like the below: ``` if (this.Option.UseIdAttribute) attributeIDs = new Hashtable(); else attributeIDs = null; public Element GetElementById(string id) { if (string.IsNullOrEmpty (id)) throw new ArgumentNullException("id"); if (attributeIDs == null) throw new Exception(ExceptionUseIdAttributeFalse); return attributeIDs[id.ToLower()] as Element; } ```

Original source