Reputation: 45
I have multiple switch statements
switch(condition1)
{
case 1:
doSomething;
break;
case 2:
doSomething;
break;
default
break;
}
--
switch(condition2)
{
case 1:
doSomething;
break;
case 2:
doSomething;
break;
default
break;
}
The conditions can increase in future eg. condition3, condition4 i.e more switch statements can be there. So i need scalability.
I want to merge these switch statements. I dont want to use alot of if,else conditions. No return statments in between to break the flow. No dynamic memory allocation. No Multi-dimensional arrays.
eg.
result = someOperation(condition1, condition2, condition3...)
switch(result)
{
case 1:
doSomething;
break;
case 2:
doSomething;
break;
default
break;
}
Specifically, i want to generate unique combination of multiple ints. Don't want string comparisons. I prefer to hide entire functionality in some design pattern ( i was not able to find one, though.)
Upvotes: 1
Views: 452
Reputation: 12668
if you need something scalable, perhaps you can implement some kind of table, indexed by condition result, that stores a pointer to the function to be called on behalf of the condition result. This way you'll get something scalable (you can modify the table dynamically, at runtime) and efficient (well, not as efficient as a switch
statement, but perhaps enough for your purposes)
In case you have to add new code for the conditions (or the last paragraph solution is not efficient enough), the most effective thing is to write a little program that generates the switch
statements for you (and perhaps #include
it on the proper place), and include this generation in the automatic building process.
Upvotes: 0
Reputation: 27365
The conditions can increase in future eg. condition3, condition4 i.e more switch statements can be there. So i need scalability.
[comment:] Strategy pattern will work, but how will i choose which strategy to choose.
Consider this:
class operation // strategy base
{
public:
virtual bool applies(int result) const = 0;
virtual void perform() = 0;
virtual ~operation() = 0;
};
class first_case: public operation // choose better name than first_case
{
public:
bool applies(int result) const override
{
return result == 1; // equivalent of "case 1:"
}
};
// other cases defined here
Client code:
void do_stuff()
{
// std::vector<std::unique_ptr<operation>> operations; defined else-where
auto result = someOperation(condition1, condition2, condition3...);
for(auto &op: operations) // equivalent of your switch above
if(op.applies(result))
{
op.perform();
break;
}
}
Basically, you implement the strategy choosing criteria as a virtual API on the operation base (and specialize it for each operation).
Upvotes: 1