0

In the below Java Code for handling xml elements i am using multiple if-else condition. What is the better way to avoid these if-else conditions where I have used "A" and "B" for condition check.

My Code :

     ...
        if(((Element)nodeValue).hasAttribute("name")) {
            String nVal = ((Element)nodeValue).getAttribute("name");
            if(nVal.equals("A")) { 
                rNodeContent = nodeValue.getTextContent();                          
                ... Processing...
            } else if(nVal.equals("B")) {
                rNodeContent = nodeValue.getTextContent();
                ... Processing...
            }
        }
     ...
5
  • I really can't see you have too many if-else clauses here, when working with files you need to use a lot of checks on the incoming data, we work with these situations a lot and it's really unavoidable to a certain extent. Only suggestion would be creating a separate method for the nVal.equals check if you want the code to look cleaner Commented May 18, 2017 at 19:08
  • If you use java 1.7 you can switch on strings. See this Commented May 18, 2017 at 19:08
  • DOM is one of the more verbose apis to use; depending on your actual usecase there is likely a better alternative. E.g. if you want to create Object from XML JAXB is a nice fit. Commented May 18, 2017 at 19:11
  • It depends on what you are doing with nVal, you might want to create a method that accepts nVal and process it there but if you use if else inside the method, it won't help either, it really depends on what you want to do with it. Commented May 18, 2017 at 19:12
  • The first 2 ifs can be combined using && Commented May 18, 2017 at 19:15

1 Answer 1

1

In Java SE 7 and later you may use switch statement for several String values as it may be a bit more readable:

String nVal = ((Element)nodeValue).getAttribute("name");
switch(nVal){
    case "A":
       // processing
       break;
    case "B":
       // processing
       break;
    default:
       throw new IllegalArgumentException("Invalid nVal value: " +nVal); 
}
Sign up to request clarification or add additional context in comments.

4 Comments

You cannot switch on strings below java 1.7
@svasa so? If he is using anything older than 7 he should update anyway.
@Fildor I know many people who still uses jre1.6, what if an old project uses jre1.6 and you need to fix a bug ? and updating it to jre1.7 is not a feasible option or not yet taken up.
@svasa, I've updated my answer to point on Java version that supports switch for strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.