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
What you’re doing here is executing a list of tests. For each test, if a predicate is true, execute an action. When a test passes, stop processing the list. Right?
A couple of people have suggested using a dictionary, but the problem with using a dictionary is that you don’t control the order of the items in it. If you want to perform the tests in a specific order (which, as stated, you do), that’s not going to work. So a list seems like the way to go.
Here’s a functional way to do this, assuming that the predicates are examining an
XmlElement.Your tests are instances of a class:
To populate the list of tests:
To execute the tests:
You’ve eliminated a lot of if/else clutter, but you’ve replaced it with this:
If your method naming is good, though, this results in pretty clean code.
To use .NET 2.0, I think you need to add this to the code:
because I think that type was defined in 3.0. I could be wrong.