The Perfect Wild Goto Statement
My boy @BillRob claims to have “a perfect example of a goto statement in the wild … and that is awesome.“ I said it wasn’t at all. I’ll humor his request in full and show him how I’d do this. Apologies for now knowing the library, but that’s immaterial.
Note: no nested if’s, no multiple exits, no unnecessary objects or assignment and better error explanation
Note 2: I don’t even write code anymore. Shame on you Bill (but you are still the MAN!).
private static string GetCDATA( XmlNode node )
{
String error = “”;
// For style reasons, I always put the constant on the lhs within an if statement
// for the compiler to automatically discover nasty undesired assignment errors
if (1 != node.ChildNodes.Count)
error = ” does not have a single child”;
// There is no reason for you to create a new XmlNode just to return the value.
// You waste time creating a new object and the assignment. Not needed.
if (XmlNodeType.CDATA != node.FirstChild.NodeType)
error += ” and the first child is not of type CDATA”;
if (0 == node.FirstChild.Value.Length)
error += ” and the first child’s value is empty”;
if (0 != error.length) {
// good return;
return node.FirstChild.Value;
}
else
// return an error that matches the exact issue
throw new ConfigurationErrorsException(node.Name + error, node);
}