<p>I'm working on an internal project for my company, and part of the project is to be able to parse various "Tasks" from an XML file into a collection of tasks to be ran later.</p>

<p>Because each type of Task has a multitude of different associated fields, I decided it would be best to represent each type of Task with a seperate class.</p>

<p>To do this, I constructed an abstract base class:</p>

<pre><code>public abstract class Task
{
    public enum TaskType
    {
        // Types of Tasks
    }   

    public abstract TaskType Type
    {
        get;
    }   

    public abstract LoadFromXml(XmlElement task);
    public abstract XmlElement CreateXml(XmlDocument currentDoc);
}
</code></pre>

<p>Each task inherited from this base class, and included the code necessary to create itself from the passed in XmlElement, as well as serialize itself back out to an XmlElement.</p>

<p>A basic example:</p>

<pre><code>public class MergeTask : Task
{

    public override TaskType Type
    {
        get { return TaskType.Merge; }
    }   

    // Lots of Properties / Methods for this Task

    public MergeTask (XmlElement elem)
    {
        this.LoadFromXml(elem);
    }

    public override LoadFromXml(XmlElement task)
    {
        // Populates this Task from the Xml.
    }

    public override XmlElement CreateXml(XmlDocument currentDoc)
    {
        // Serializes this class back to xml.
    }
}
</code></pre>

<p>The parser would then use code similar to this to create a task collection:</p>

<pre><code>XmlNode taskNode = parent.SelectNode("tasks");

TaskFactory tf = new TaskFactory();

foreach (XmlNode task in taskNode.ChildNodes)
{
    // Since XmlComments etc will show up
    if (task is XmlElement)
    {
        tasks.Add(tf.CreateTask(task as XmlElement));
    }
}
</code></pre>

<p>All of this works wonderfully, and allows me to pass tasks around using the base class, while retaining the structure of having individual classes for each task.</p>

<p>However, I am not happy with my code for TaskFactory.CreateTask. This method accepts an XmlElement, and then returns an instance of the appropriate Task class:</p>

<pre><code>public Task CreateTask(XmlElement elem)
{
    if (elem != null)
    {
        switch(elem.Name)
        {
            case "merge":
                return new MergeTask(elem);
            default:
                throw new ArgumentException("Invalid Task");
        }
    }
}
</code></pre>

<p>Because I have to parse the XMLElement, I'm using a huge (10-15 cases in the real code) switch to pick which child class to instantiate. I'm hoping there is some sort of polymorphic trick I can do here to clean up this method.</p>

<p>Any advice?</p>

[{'answer_id': 27310, 'author': 'DevelopingChris', 'author_id': 1220, 'author_profile': 'https://Stackoverflow.com/users/1220', 'pm_score': 5, 'selected': True, 'text': '<p>I use reflection to do this.\nYou can make a factory that basically expands without you having to add any extra code.</p>\n\n<p>make sure you have "using System.Reflection", place the following code in your instantiation method.</p>\n\n<pre><code>public Task CreateTask(XmlElement elem)\n{\n    if (elem != null)\n    { \n        try\n        {\n          Assembly a = typeof(Task).Assembly\n          string type = string.Format("{0}.{1}Task",typeof(Task).Namespace,elem.Name);\n\n          //this is only here, so that if that type doesn\'t exist, this method\n          //throws an exception\n          Type t = a.GetType(type, true, true);\n\n          return a.CreateInstance(type, true) as Task;\n        }\n        catch(System.Exception)\n        {\n          throw new ArgumentException("Invalid Task");\n        }\n    }\n}\n</code></pre>\n\n<p>Another observation, is that you can make this method, a static and hang it off of the Task class, so that you don\'t have to new up the TaskFactory, and also you get to save yourself a moving piece to maintain.</p>\n'}, {'answer_id': 27320, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 1, 'selected': False, 'text': '<p>@ChanChan</p>\n\n<p>I like the idea of reflection, yet at the same time I\'ve always been shy to use reflection. It\'s always struck me as a "hack" to work around something that should be easier. I did consider that approach, and then figured a switch statement would be faster for the same amount of code smell.</p>\n\n<p>You did get me thinking, I don\'t think the Type enum is needed, because I can always do something like this:</p>\n\n<pre><code>if (CurrentTask is MergeTask)\n{\n    // Do Something Specific to MergeTask\n}\n</code></pre>\n\n<p>Perhaps I should crack open my GoF Design Patterns book again, but I really thought there was a way to polymorphically instantiate the right class.</p>\n'}, {'answer_id': 27324, 'author': 'DevelopingChris', 'author_id': 1220, 'author_profile': 'https://Stackoverflow.com/users/1220', 'pm_score': 2, 'selected': False, 'text': '<p>@jholland</p>\n\n<blockquote>\n  <p>I don\'t think the Type enum is needed, because I can always do something like this:</p>\n</blockquote>\n\n<p>Enum?</p>\n\n<p>I admit that it feels hacky. Reflection feels dirty at first, but once you tame the beast you will enjoy what it allows you to do. (Remember recursion, it feels dirty, but its good)</p>\n\n<p>The trick is to realize, you are analyzing meta data, in this case a string provided from xml, and turning it into run-time behavior. That is what reflection is the best at.</p>\n\n<p><strong>BTW: the is operator, is reflection too.</strong></p>\n\n<p><a href="http://en.wikipedia.org/wiki/Reflection_(computer_science)#Uses" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Reflection_(computer_science)#Uses</a>  </p>\n'}, {'answer_id': 27328, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 1, 'selected': False, 'text': "<blockquote>\n  <p>Enum?</p>\n</blockquote>\n\n<p>I was referring to the Type property and enum in my abstract class.</p>\n\n<p>Reflection it is then! I'll mark you answer as accepted in about 30 minutes, just to give time for anyone else to weigh in. Its a fun topic.</p>\n"}, {'answer_id': 27331, 'author': 'DevelopingChris', 'author_id': 1220, 'author_profile': 'https://Stackoverflow.com/users/1220', 'pm_score': 1, 'selected': False, 'text': "<p>Thanks for leaving it open, I won't complain. It is a fun topic, I wish you could polymorphicly instantiate.<br>\nEven ruby (and its superior meta-programming) has to use its reflection mechanism for this.</p>\n"}, {'answer_id': 27339, 'author': 'Dale Ragan', 'author_id': 1117, 'author_profile': 'https://Stackoverflow.com/users/1117', 'pm_score': 2, 'selected': False, 'text': '<p>How do you feel about Dependency Injection?  I use Ninject and the contextual binding support in it would be perfect for this situation.  Look at this <a href="https://web.archive.org/web/20081025114811/http://kohari.org/2008/03/13/context-variables-in-ninject/" rel="nofollow noreferrer">blog post</a> on how you can use contextual binding with creating controllers with the IControllerFactory when they are requested.  This should be a good resource on how to use it for your situation.</p>\n'}, {'answer_id': 27360, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 1, 'selected': False, 'text': "<p>@Dale</p>\n\n<p>I have not inspected nInject closely, but from my high level understanding of dependency injection, I believe it would be accomplishing the same thing as ChanChans suggestion, only with more layers of cruft (er abstraction).</p>\n\n<p>In a one off situation where I just need it here, I think using some handrolled reflection code is a better approach than having an additional library to link against and only calling it one place...</p>\n\n<p>But maybe I don't understand the advantage nInject would give me here.</p>\n"}, {'answer_id': 27378, 'author': 'Dale Ragan', 'author_id': 1117, 'author_profile': 'https://Stackoverflow.com/users/1117', 'pm_score': 1, 'selected': False, 'text': '<p>Some frameworks may rely on reflection where needed, but most of the time you use a boot- strapper, if you will, to setup what to do when an instance of an object is needed.  This is usually stored in a generic dictionary.  I used my own up until recently, when I started using Ninject.</p>\n\n<p>With Ninject, the main thing I liked about it, is that when it does need to use reflection, it doesn\'t.  Instead it takes advantage of the code generation features of .NET which make it incredibly fast.  If you feel reflection would be faster in the context you are using, it also allows you to set it up that way.</p>\n\n<p>I know this maybe overkill for what you need at the moment, but I just wanted to point out dependency injection and give you some food for thought for the future.  Visit the <a href="http://dojo.ninject.org/wiki/display/NINJECT/Home" rel="nofollow noreferrer">dojo</a> for a lesson.</p>\n'}, {'answer_id': 27429, 'author': 'Tim Williscroft', 'author_id': 2789, 'author_profile': 'https://Stackoverflow.com/users/2789', 'pm_score': 3, 'selected': False, 'text': '<p>Create a "Prototype" instanace of each class and put them in a hashtable inside the factory , with the string you expect in the XML as the key.</p>\n\n<p>so CreateTask just finds the right Prototype object,\nby get() ing from the hashtable.</p>\n\n<p>then call LoadFromXML on it.</p>\n\n<p>you have to pre-load the classes into the hashtable,</p>\n\n<p>If you want it more automatic...</p>\n\n<p>You can make the classes "self-registering" by calling a static register method on the factory.</p>\n\n<p>Put calls to register ( with constructors) in the static blocks on the Task subclasses.\nThen all you need to do is "mention" the classes to get the static blocks run.</p>\n\n<p>A static array of Task subclasses would then suffice to "mention" them.\nOr use reflection to mention the classes.</p>\n'}, {'answer_id': 28659, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': '<p>@Tim, I ended up using a simplified version of your approach and ChanChans, Here is the code:</p>\n\n<pre><code>public class TaskFactory\n    {\n        private Dictionary&lt;String, Type&gt; _taskTypes = new Dictionary&lt;String, Type&gt;();\n\n        public TaskFactory()\n        {\n            // Preload the Task Types into a dictionary so we can look them up later\n            foreach (Type type in typeof(TaskFactory).Assembly.GetTypes())\n            {\n                if (type.IsSubclassOf(typeof(CCTask)))\n                {\n                    _taskTypes[type.Name.ToLower()] = type;\n                }\n            }\n        }\n\n        public CCTask CreateTask(XmlElement task)\n        {\n            if (task != null)\n            {\n                string taskName = task.Name;\n                taskName =  taskName.ToLower() + "task";\n\n                // If the Type information is in our Dictionary, instantiate a new instance of that task\n                Type taskType;\n                if (_taskTypes.TryGetValue(taskName, out taskType))\n                {\n                    return (CCTask)Activator.CreateInstance(taskType, task);\n                }\n                else\n                {\n                    throw new ArgumentException("Unrecognized Task:" + task.Name);\n                }                               \n            }\n            else\n            {\n                return null;\n            }\n        }\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/27294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1965/']