Parsing XML object to multiple classes with different logic

折月煮酒 提交于 2019-12-13 05:28:57

问题


I have a lot of XML nodes generated by a 3rd party:

<node id='8440' name='nodeOne' property_two='7.22' sorting_index='20'/>
<node id='8440' name='nodeTwo' property_two='7.22' sorting_index='subItemThree;30;subItemTwenty;50'/>
...

Every attribute has the same type and meaning among all nodes except one named sorting_index. Usually, it contains an int indicating, well, object's sorting index. In the first node above sorting index is 20 for an object named "nodeOne".

Unfortunately, sometimes those nodes are just "carriers" of a sorting index for multiple subobjects. Looking into a second node given above, we can see that it provides sorting indeces for objects named "subItemThree" and "subItemTwenty" with values 30 and 50 respectively.

Im my approach, I created two classes with first being a representation of a node with simple sorting_index and second class being a representation of a node with the complicated sorting_index logic. Second class extended the first one and added a method to extract an array of sorting indeces from SortingIndex property's getter. So what I did is I parsed everything to a base class (SortingIndex property is of string type) and then converted some of them to a derived class. I've described the logic behind this in another question: Converting from base to derived object while having a huge constructor definition

However, I was told that having such a conversion is not a good design approach. What are your suggestions? I feel like having 2 totally independent classes with absolutely same logic except for one property is an overkill.


回答1:


Whether one should inherit from the other you should consider whether the derived class is substitutable for the base class, see the Liskov substitution principle

If its not, you could try something like this with a common base class that has all the properties apart from the sort index.

public abstract class BaseClass
{
    public string Property1 { get; }
    public int Property2 { get; }

    public BaseClass(string prop1, int prop2)
    {
        ...
    }
}

public class StringClass : BaseClass
{
    public int SortIndex { get; }

    public StringClass(string prop1, int prop2, int index) :
        base(prop1, prop2)
    {
        SortIndex = index;
    }
}

public class CollectionClass : BaseClass
{
    public Dictionary<string, int>  SortIndexes { get;}

    public CollectionClass(string prop1, int prop2, Dictionary<string, int> indexes) :
        base(prop1, prop2)
    {
        SortIndexes = indexes;
    }
} 


来源:https://stackoverflow.com/questions/53060487/parsing-xml-object-to-multiple-classes-with-different-logic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!