0

I really like the ease and flexibility of using XmlSerializer to persist configuration data for my application. However, I can see potential maintainability issues.

From looking at my class definitions, it is not obvious that the reason certain fields are exposed as properties is for serialization purposes. Somebody could come along and remove a property (leaving the private field alone) and inadvertently cause issues due to important information no longer being serialized to XML.

I could add comments to explain this, but I'd rather the code spoke for itself.

There exists the [Serializable] attribute (which hints that the class is to be serialized), but this isn't actually required for the XmlSerializer and is therefore unnecessary.

I could write some custom serialization code but then I lose the simplicity of using XmlSerializer.

Is there a way of decorating my code to make it clear which classes and which properties are candidates for XML serialization?

digital_fate
  • 567
  • 1
  • 5
  • 15
  • Picking good names solves 90% of this kind problem. You can for example append "Serialized" to the class name to make it blindingly obvious that it is serialized. – Hans Passant Jun 22 '16 at 09:30
  • why "Somebody could come along and remove a property"? – Tommy Jun 22 '16 at 09:33
  • @Tommy I'm thinking of future developers 'tidying' the code. I'm just trying to make my implementation as bullet-proof as possible. – digital_fate Jun 22 '16 at 09:40
  • @HansPassant That's a simple idea I didn't think of. It leaves a slightly bad taste in my mouth due to the number of classes that will be serialized and therefore the number of class names suffixed with "Serialized", but maybe I'm just being picky. – digital_fate Jun 22 '16 at 09:45
  • Well, count that as yet another benefit. Programmers ought to feel uneasy about writing a lot of code that is difficult to modify. – Hans Passant Jun 22 '16 at 09:55
  • I agree - it's the reason I'm asking the questions. I think custom serialization might be a better choice. Slightly more work now but at least it makes explicit exactly what is being serialized. – digital_fate Jun 22 '16 at 10:10
  • 1) Add a unit test for each class that [serializes an instance of each class to an `XElement`](https://stackoverflow.com/questions/37443397/serialize-object-to-xml-within-a-parent-element) then uses Linq-to-XML to verify the expected elements are present. 2) Mark the public properties with `[XmlElement]` (or `[XmlArray]` or `[XmlAttribute]` as appropriate) to hint that they are serialized. – dbc Jul 02 '16 at 18:40

0 Answers0