Small Project Organization
Command Dispatch
An enum and a switch make command handling explicit.
Command Dispatch
command_dispatch.cpp
#include <iostream>
enum class Command {
Start,
Stop,
Pause
};
Command decode(int code) {
if (code == 1) {
return Command::Start;
}
if (code == 2) {
return Command::Stop;
}
return Command::Pause;
}
int main() {
int code = ;
Command command = decode(code);
int action = 0;
switch (command) {
case Command::Start:
action = 10;
break;
case Command::Stop:
action = 20;
break;
case Command::Pause:
action = 30;
break;
}
std::cout << "code=" << code << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
#include <iostream>
enum class Command {
Start,
Stop,
Pause
};
Command decode(int code) {
if (code == 1) {
return Command::Start;
}
if (code == 2) {
return Command::Stop;
}
return Command::Pause;
}
int main() {
int code = ;
Command command = decode(code);
int action = 0;
switch (command) {
case Command::Start:
action = 10;
break;
case Command::Stop:
action = 20;
break;
case Command::Pause:
action = 30;
break;
}
std::cout << "code=" << code << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
#include <iostream>
enum class Command {
Start,
Stop,
Pause
};
Command decode(int code) {
if (code == 1) {
return Command::Start;
}
if (code == 2) {
return Command::Stop;
}
return Command::Pause;
}
int main() {
int code = ;
Command command = decode(code);
int action = 0;
switch (command) {
case Command::Start:
action = 10;
break;
case Command::Stop:
action = 20;
break;
case Command::Pause:
action = 30;
break;
}
std::cout << "code=" << code << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
enum
Use an enum when a value must be one of a small named set.
dispatch
A switch turns the command into the project action that should happen next.