James MV
James MV

Reputation: 8727

Condensing a switch statement?

Something I've wondered for awhile as it seems to crop up in my in-experienced code quite a bit.

I have some code that uses a switch statement a lot, but all its really doing is accessing a different queue each time.

void store(int toSwitchOn, float posx, float posy){ 
    myDataStruct newValue;
    newValue.psX = posx;
    newValue.psY = posy;

    switch(toSwitchOn){
        case 1:
            queue1.push(newValue);          
            break;
        case 2:
            queue2.push(newValue);          
            break;
        case 3:
            queue3.push(newValue);
            break;
        case 4:
            queue4.push(newValue);
            break;
        case 5:
            queue5.push(newValue);
            break;
    }


}

The only thing that changes in each statement is the queue variable. Is there some ingenious way to condense this sort of repetitive code?

Upvotes: 0

Views: 468

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24153

The obvious answers are to replace the switch with a vector or map lookup of the thing to switch on.

However, I see coupling between the integer and the vector index as a leaky interface.

I want to know how the caller of this function knows which integer value to use. Who told them what to use? Could they have just been given a reference to a Storage object instead?

Replace:

int function_telling_which_index_to_use_for_storage();

With:

Storage* storage_to_use();

Then you can say:

Storage* storage = storage_to_use();
// ...
storage->store(posx, posy);

Remember: encapsulate, encapsulate, encapsulate.

Upvotes: 0

clanmjc
clanmjc

Reputation: 299

std::vector<std::queue<someType> > queues (5); 
//toSwitchOn is of type size_t and zero indexed.
... 
if (toSwitchOn < queues.size())
   queue [toSwitchOn].push (newValue);  //0 - 1 = undefined land...     
else     //default switch case 

Upvotes: 0

Qaz
Qaz

Reputation: 61970

Store your queues in a vector.

std::vector<std::queue<someType> > queues (5);
//fill vector with your 5 queues

//this replaces the switch:
if (toSwitchOn >= 1 && toSwitchOn <= 5)
    queue [toSwitchOn - 1].push (newValue);
else
    //default switch case

Upvotes: 5

Related Questions