1

I have a static class that performs xml serialization. Is it better for the static class to be responsible/implement for converting objects of type foo to their proper xml representation or to have foo implement its own foo.ToXml() method? The conversion just transfers information regarding foo into a data class with correct XmlAttribute and XmlElement properties.

Essentially:

var fooData = XmlClass.Convert(foo)

or

var fooData = foo.ToXml()
1
  • The answer to this question will depend greatly on how "standard" your XML representation is with respect to the Foo class. If everything translates one-to-one, then a separate class that can introspect Foo is more than sufficient. Otherwise, ... Commented Aug 20, 2019 at 19:32

2 Answers 2

3

C# supports reflection, so you can write a solution to take advantage using introspection. You would use XmlClass.Convert to convert foo (or any class).

In more general terms (and not specific to C#), if you are using a language that does not support reflection you should have foo do the conversion. This is because foo knows the details of what a foo is; XmlClass does not, nor should it. foo should implement a ToXml method to convert its data to an XML string. It won't do this in isolation, and can (should) call helper methods in XmlClass to convert standard data types (like Int and String) to XML. Having a ToXml method is also helpful because the XML conversion code is in the class, and any future changes to the class are less likely to miss updating the XML conversion code.

If you have XmlClass to the conversion, then XmlClass needs to know the details of foo. This will cause a coupling between the two classes that does not need to exist, and increase the likelihood of bugs when changes are made to foo and the XML conversion code is not updated. This would also violate the idea of Separation of Concerns.

0
0

C# supports extension methods. So you can effectively employ both solutions together; no need to choose:

static class XmlConverters
{
    static Xml ToXml(this Foo foo)
    {
        ...
    }
}

and then use it as var fooData = foo.ToXml().

Not the answer you're looking for? Browse other questions tagged or ask your own question.