maaboo
maaboo

Reputation: 137

Compacting the code: same action for any element of a pair

Is there any way to make code more compact for this situation?

// 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++?

One more example:

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++;             
        }
    }
}

Is it possible to use only one if or more clear construction?

Upvotes: 1

Views: 81

Answers (2)

vakio
vakio

Reputation: 3177

for 2nd example:

checkBody(bodyA);
checkBody(bodyB);

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

Upvotes: 3

raven
raven

Reputation: 2564

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

Upvotes: -1

Related Questions