tags:

views:

54

answers:

3

Should functions that act on and object, say to fill it out from xml, belong to the object itself or should whatever is creating the object own these function?

+2  A: 

A class should generally have only one purpose (called the Single Responsibility Principle). So while an object will often have methods that act on its own data, you should be conservative in terms of what that is. In the case of reading data into an object instance, that probably deserves another class.

So if you have a class A and you want to get data from XML and instantiate instances of A, that should be a separate class most likely. Something like AXmlReader for example. It could then implement an AReader interface and you could have an ADBReader, etc.

geofflane
+1  A: 

This sounds to me like a static factory method, i.e. something like

public static SomeObject CreateSomeObjectFromDataReader (IDataReader queryResult)
{
    // create SomeObject by populating the fields using the IDataReader
}

in which case, it should be owned by the class itself since its implementation is specific to that class (and it would have access to private setters of properties).

jpoh
+1  A: 

I would combine the answers of geofflane and jpoh, which are both good.

The Single Responsibility Principle is important, but you need to weigh the benefits of responsibility-splitting and abstraction with the costs of readability and code maintenance. Do you really need to create 4 new classes to hydrate an object from XML?

Eh... I'd probably lean toward a simple Factory Method pattern implementation, as well.

It depends on the application of your code, but I might have a SomeObjectFactory class with a CreateSomeObject(XmlReader reader) method instead of making this the responsibility of the SomeObject class.

public class SomeObjectFactory
{
    public static SomeObject CreateSomeObject(XmlReader reader)
    {
     //hydrate a new SomeObject
    }
}

Good luck!

Kevin Swiber