Reputation: 5301
I am having a design issue:
i have following sets of integers for some commands like:
addition = {2,3,4,5}
subtraction = {3,6,9}
where priority of add is > that of sub.
so i created a class like
class Command{
int priority;
public:
bool operator <(const Command &com);
bool isInSet(int);
// i donot want this to be int ,
// may be tommorrow i go for strings or char.
// How to do this. AND
void execute(int); // should it be here?
};
As these commands operate on a data structure.
Should every command know how to execute iteself i.e. should there be a function inseide the command itself.
If execute() goes inside the Command, how would it access the data structure? So Command should also have a pointer to this DS.
Or should be it a pair but then class Execution would require pointer to DS.
Or should it be like Command sends me some enum and then i switch it to do something like
enum {PUSH, POP};
while(!commands[i].isInSet(3))
++i;
switch(comands[i].getName())
{
case PUSH:
// operations on DS i have all of them in this scope. :)
case POP:
...
}
What should i do ?
Is there any other good method ? Thanks.
Upvotes: 0
Views: 108
Reputation: 648
I'm not sure I get your question very well, but:
Should every command know how to execute iteself i.e. should there be a function inseide the command itself.
I think - yes. I'd include the logic of the command as a method of the class. You want to use different structure, so I'd create an abstract base class, acting as interface for the data type. The command will accept pointer to the base class and perform it's operations on it using the interface.
If execute() goes inside the Command, how would it access the data structure? So Command should also have a pointer to this DS.
Yes, I think this is perfectly okay.
Or should it be like Command sends me some enum and then i switch it to do something like
If you'll have switch on many places, I think you should avoid it. If it'll be on one place only - maybe it is okay. But generally speaking I'd avoid this approach, because it makes adding new types hard. You forget one switch and then debug for hours.
Upvotes: 1