2012-01-20 39 views
1

有沒有什麼辦法可以讓代碼更緊湊?壓縮代碼:一對任何元素的相同動作

// pseudocode 
if (A == 1) { 
    if (B == 2) { 
     action1; 
    } 
    if (B == 3) { 
     action2; 
    } 
} 

if (B == 1) { 
    if (A == 2) { 
     action1; 
    } 
    if (A == 3) { 
     action2; 
    } 
} 

in Objective-C/Objective-C++?

再舉一個例子:

if (((int)fixtureUserDataA == FIXTURE_FOOT_SENSOR || ((int)fixtureUserDataB == FIXTURE_FOOT_SENSOR))) { 

    // Hero foot sensors 
    if (bodyA->GetUserData() != NULL) { 
     CCSprite * sprite = (CCSprite*)bodyA->GetUserData(); 
     if (sprite.tag == TAG_HERO) { 
      [Hero sharedInstance].numFootContacts++;    
     } 
    } 

    if (bodyB->GetUserData() != NULL) { 
     CCSprite * sprite = (CCSprite*)bodyB->GetUserData(); 
     if (sprite.tag == TAG_HERO) { 
      [Hero sharedInstance].numFootContacts++;    
     } 
    } 
} 

是否有可能只使用一個,如果還是更清晰建設?

回答

-1
if (A == 1 || B == 1) 
    if (A + B == 3) 
     action1; 
    else if (A + B == 4) 
     action2; 
3

爲第二示例:

checkBody(bodyA); 
checkBody(bodyB); 

void checkBody(Body* body) 
{ 
    CCSprite * sprite = (CCSprite*)body->GetUserData(); 
     if (sprite.tag == TAG_HERO) { 
      [Hero sharedInstance].numFootContacts++;    
     } 
}