Context:
I have a case where I need to extend some existing functionality for loading a new version of an xml file into a system (new fields, some mandatory that were not mandatory before, etc). The file contains some heavy information, but to keep things simple I will use a simple case.
The xml file can be something like this.
Version 1 (used in current implementation):
<?xml version="1.0" encoding="utf-8"?>
<version value="1" />
<items>
<item name="item1">
<subitem name="subitem1" value="value1"/>
<subitem name="subitem2"/>
</item>
</items>
Version 2 (new version, not implemented yet):
<?xml version="1.0" encoding="utf-8"?>
<version value="2" />
<items>
<item name="item1">
<subitem name="subitem1" value="value1" description="sub item 1"/>
<subitem name="subitem2" value="value2"/>
</item>
</items>
- In Version 1 the value property in subitem is not mandatory.
- In Version 2 the value property in subitem is mandatory, and there is a new optional property called description.
Current Implementation:
Currently, the system was developed with hard coded classes (because of some complexity during class matching between the xml and the db), and for the mandatory value validation, a custom attribute was used.
Something like this (only import/export of XML Version 1 is supported):
public class Item
{
[Mandatory]
public string Name {get;set;}
public IList<SubItem> SubItems {get;set;}
}
public class SubItem
{
[Mandatory]
public string Name {get;set;}
public string Value {get;set;}
}
This was also developed like this, because at some point during the validation process, the missing properties will be shown to the user so the user can fix them right away (by inserting the value in a TextBox for example).
The problem of having this structure is that a new version that needs to change which properties are Mandatory or not, requires changing the current implementation, and of course would not work for previous versions.
There are currently no XSD schemas for either version, just a document defining this new version (which fields are mandatory, which ones are new, etc).
Possible approaches:
One option I have is to change the class definition to be abstract, and override the properties that changed in a new version, but if there are multiple new versions it will become hard to read and hard to follow (multiple versions, with multiple properties changed, and multiple validations changed for the property), so I'm not sure this is a good approach.
Another approach is to remove the custom attributes, and add another layer of validation using something different (but I'm not entirely certain as to what to use). Possibly using a strategy pattern with methods for validation depending on the version.
Question:
How else can this problem be addressed? Is there a design pattern that I can follow for this type of scenarios?
Your help is much appreciated.