Is there a more intelligent way to do this besides a long chain of if statements or switch?

Posted by Harrison Nguyen on Programmers See other posts from Programmers or by Harrison Nguyen
Published on 2014-06-13T06:49:32Z Indexed on 2014/06/13 9:40 UTC
Read the original article Hit count: 348

Filed under:
|

I'm implementing an IRC bot that receives a message and I'm checking that message to determine which functions to call. Is there a more clever way of doing this? It seems like it'd quickly get out of hand after I got up to like 20 commands.

Perhaps there's a better way to abstract this?

 public void onMessage(String channel, String sender, String login, String hostname, String message){

        if (message.equalsIgnoreCase(".np")){
//            TODO: Use Last.fm API to find the now playing
        } else if (message.toLowerCase().startsWith(".register")) {
                cmd.registerLastNick(channel, sender, message);
        } else if (message.toLowerCase().startsWith("give us a countdown")) {
                cmd.countdown(channel, message);
        } else if (message.toLowerCase().startsWith("remember am routine")) {
                cmd.updateAmRoutine(channel, message, sender);
        }
    }

© Programmers or respective owner

Related posts about design

Related posts about abstraction