dimanche 10 mars 2019

Object creation based on a String

Let's say I'm writing a bot for a chat (discord, telegram, whatever). The bot can handle chat commands (e.g. !join tells it to join a voice channel on the server).

So somewhere in my code I'd have to parse the command, and I'll have something like

String userMessage = getTheMessageTextSomehow();
// Do something with the  message.

I'd like to have a Command class for every one of my commands, and every command would implement a execute() method.

My question is: what's the best practice to create those command objects?

The easiest way would be to have a large CommandFactory or whatever class somwhere, that would be like

if(message.equals(JOIN_MESSAGE) {
    return new JoinCommand();
} 
if(message.equals(LEAVE_MESSAGE){
    return new LeaveCommand();
}
//etc...

That looks like a bad practice and code smell to me. Is there a better way to do it?

Aucun commentaire:

Enregistrer un commentaire