views:

1028

answers:

3

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?

+1  A: 

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.

OregonGhost
+3  A: 

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.

Greg Hewgill
Thank you. Is it considered acceptable to (at least in limited cases where I'm only loading this particular type) create a Factory method inside the same class as the method being loaded? For whatever reason, I was under the impression factories usually had their own classes.
AlexeyMK
Certainly, you can create a static factory method within the class itself. You only need the higher level factory abstraction if you have a whole tree of potential objects to deal with. For your situation, just make a static method that returns a newly allocated instance of your class.
Greg Hewgill
+2  A: 

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

Jon Skeet