Question

Greetings,

I have a particular object which can be constructed from a file, as such:

public class ConfigObj
{
     public ConfigObj(string loadPath)
     {
          //load object using .Net's supplied Serialization library
          //resulting in a ConfigObj object
          ConfigObj deserializedObj = VoodooLoadFunction(loadpath); 

          //the line below won't compile
          this = thisIsMyObj; 
     }
}

I want to, in essense, say "ok, and now this object we've just deserialized, this is the object that we in fact are." There are a few ways of doing this, and I'm wondering which is considered a best-practice. My ideas are:

  • Build a copy-into-me function which copies the object field by field. This is the current implementation and I'm pretty sure its a horrible idea since whenever a new member is added to the object I need to also remember to add it to the 'copy-into-me' function, and there's no way that's maintainable.
  • Build a static method for the ConfigObj class which acts as a de-facto constructor for loading the object. This sounds much better but not very best-practice-y.

I'm not entirely happy with either of the two, though. What is the acknowledged best practice here?

Was it helpful?

Solution

Your second option is what is called a factory method and is a common design technique. If you do use this technique, you may find that you need to know the type of class you will load before you actually load the class. If you run into this situation, you can use a higher level type of factory that looks at the stream and calls the factory method for the appropriate type of class.

OTHER TIPS

There's nothing wrong with having a static method instead of a constructor. In fact, it has a number of advantages.

I always go with the static method. Usually it's kind of a hierarchy which is loaded, and therefore only the root object needs the method. And it's not really an unusual approach in the .NET framework (e.g. Graphics.FromImage), so it should be fine with users of your class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top