Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I optimize the if condition in this snippet? The only one difference is && [self isCurrentPosition:i]. How can I make it a single if, including the condition val?

Note: self is a category of NSArray.

- (void) cleanTextfieldExcluding:(int)current checkPosition:(BOOL)val {
  for ( int i=0; i<[self count]; i++ ) {

    // -----------
    if ( val ) {  // this IF block is very bad
      if ( i != current && [self isCurrentPosition:i] )
        [self replaceObjectAtIndex:i withObject:@""];
    } else {
      if ( i != current ) 
        [self replaceObjectAtIndex:i withObject:@""];
    }
    // -----------

  }
}
share|improve this question
    
you cannot merge it go a single if. – zdd Nov 28 '12 at 10:18
up vote 3 down vote accepted

It seems that the code in if will be executed only if i != current and val && [self isCurrentPosition:i] or !val, so you could merge all the ifs into one:

- (void) cleanTextfieldExcluding:(int)current checkPosition:(BOOL)val {
  for ( int i=0; i<[self count]; i++ ) {

    // -----------
    if ( (i != current) && (!val || [self isCurrentPosition:i]) ) {
        [self replaceObjectAtIndex:i withObject:@""];
    }
    // -----------

  }
}
share|improve this answer
    
just saw the answer below me and OMG it was better than mines(performs one less logic operation) so i updated mines too. :P – namehere Nov 28 '12 at 15:32
    
-1. Your answers are now the same because you copied his code (and didn't upvote his answer). – seand Nov 28 '12 at 16:29

the (val · ¬cur · pos) | (¬val · ¬cur) = ¬cur (val·pos | ¬val) = ¬cur (pos | ¬val). So, the condition is

if ( (i != current) && (!val || [self isCurrentPosition:i]) ) {
        [self replaceObjectAtIndex:i withObject:@""];
    }

You just must practise factoring out the common subexpressions and subprograms and learn how to use the Carnot maps for boolean minimization.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.