Coming out of the habit of writing ifs/elseifs for

2020-07-23 06:55发布

When parsing an xml document for its nodes or attributes, if the document is large, I would have a bunch of ifs and else statements.

Obviously, 100+ ifs does not make up maintainable code in the long run.

Rather than doing this, is there another better way? I read on Hanselman's blog about a friend of his who had the same situation and wrote loads of ifs/else if and generally poor code. Hanselman provided some snippets of a more maintainable way but the entire code isn't available so it's a little hard to understand exactly what (the whole picture) is going on. Life after if, else

I am using .NET 3.5 SO I have the full power of extension methods and LINQ available to me. However, I use .NET 2.0 a work so would also appreciate any solutions in v2.0. :)

My code looks very similar to the problem on Hanselman's site:

if (xmlNode.Attributes["a"].Value == "abc" {

}
else if (xmlNode.Attributes["b"].Value == "xyz"
{
wt = MyEnum.Haze;
}

I could just have a dictionary storing the values I am looking for as keys and perhaps a delegate in the value (or whatever I want to happen on finding a required value), so I could say if (containskey) get delegate and execute it, in pseudocode.

This sort of thing goes on and on. Obviously very naive way of coding. I have the same problem with parsing a text document for values, etc.

Thanks

标签: c#
8条回答
孤傲高冷的网名
2楼-- · 2020-07-23 07:36

It's a bit hard to tell what you need to do. If it's to set one variable based on an XML attribute then the one line approach Hanselman alluded to is the most elegant.

MyEnum wt = (MyEnum)Enum.Parse(typeof(MyEnum), xmlNode.Attributes["a"].Value, true);  

From the brief example you provided it looks like you may need to set the variable based on different XML attributes and if that's the case you may not be able to get around the need for a big if/else block.

If you do have a semblance of structure in the XML you are processing it can sometimes be easier to process an XML node as a DataRow. If your XML is all over the place then this approach isn't much good.

DataSet xmlDerivedSet = new DataSet();
xmlDerivedSet.ReadXml(xmlFilename);

foreach (DataRow row in xmlDerivedSet.Tables[0].Rows)
{
    MyClass xmlDerivedClass = new MyClass(row);
}
查看更多
我只想做你的唯一
3楼-- · 2020-07-23 07:41

If you are doing processing for each big node, you might also want to have some specific typed xml reader classes to more cleanly integrate separate it from the actual logic of the application.

Lets say the processing you are doing is for some good amount of customer data you are receiving in Xml. You could define a class like:

public class CustomerXmlReader
{
    public class CustomerXmlReader(XmlReader xml){}
    public Customer Read()
    { // read the next customer
    }
}

This way the rest of the application just keep working with the Customer object, and you avoid mixing it with the Xml processing.

查看更多
登录 后发表回答