Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • Last Modified:

Streamlining the if condition

Hi,

I have a Piece of code with lot of if condition complexity and some more. Here is the sample one

if(isEnable("xxxxx")){
				
	if(isEnable("yyyyy")){
	
		if("zzzz".equalsIgnoreCase(tttt)){
	
			enableFlag("QuestionUserRole");
			xxxxxUserRole=new SAXQuestionUserRole();
			        	}
						
					}
                     else if("useryyyyy".equalsIgnoreCase(tttt)) {
						
                        enableFlag("yyyyy");
			useryyyyy = new LinkedHashSet<SAXQuestionUserRole>();
					}

Open in new window


My Approach would be like this below, can some body pls verify is this correct way to do that instead the above one

if(isEnable("xxxxx")) && (isEnable("yyyyy")) && (("zzzz".equalsIgnoreCase(tttt))
	              {
			enableFlag("QuestionUserRole");
			xxxxxUserRole=new SAXQuestionUserRole();
			        	}
		 
 else if (("useryyyyy".equalsIgnoreCase(tttt))  
                        {

                        enableFlag("yyyyy"); 
			useryyyyy = new LinkedHashSet<SAXQuestionUserRole>();
			}

Open in new window

0
roy_sanu
Asked:
roy_sanu
3 Solutions
 
dpearsonCommented:
No I think it should be:

if(isEnable("xxxxx")) && (isEnable("yyyyy")) && (("zzzz".equalsIgnoreCase(tttt)) {
}
else  if (isEnable("xxxxx")) && (!isEnable("yyyyy")) && (("useryyyyy".equalsIgnoreCase(tttt)) {
}

Better to write this as:

boolean x = isEnable("xxxxx") ;
boolean y = isEnable("yyyyy") ;
boolean z = ("zzzz".equalsIgnoreCase(tttt) ;
boolean userY = ("useryyyyy".equalsIgnoreCase(tttt) ;

// So then the ifs become easy to read:
if (x && y && z) {
   ...
}
else if (x && !y && userY) {
   ...
}

Doug
0
 
Peter KwanCommented:
For the original code, it should be re-format like this:

if(isEnable("xxxxx")) {
   if (isEnable("yyyyy") && "zzzz".equalsIgnoreCase(tttt)) {
      enableFlag("QuestionUserRole");
      xxxxxUserRole=new SAXQuestionUserRole();
   }
  else if ("useryyyyy".equalsIgnoreCase(tttt)) {
      enableFlag("yyyyy");
      useryyyyy = new LinkedHashSet<SAXQuestionUserRole>();
  }
}

Open in new window


P.S. The closing brace is missing in the original code.
0
 
krakatoaCommented:
You can also think about what the ternary operator might offer, such as :

boolean b = isEnable("xxxxx") ? (isEnable("yyyyy")&&("zzzz".equalsIgnoreCase("zzzz"))?true:false):false;

if(!b&&"useryyyyy".equalsIgnoreCase("useryyyyy")){
     //;	
}

Open in new window

0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now