I'm writing an application to receive SMS messages via an HTTP gateway. The main parameters I'll be processing are the sender's phone number and the message itself. However, depending on the keyword within the message, I'll need to execute different logic / return a different response. To start with, I used a simple if/else which turned into a switch statement, and now I'm looking to clean it up a bit.
I think what want is some sort of implementation of the command pattern, but I'm not sure. I could implement each operation as a command object and register them all with the command processor, but then I'd have to implement something like a CanExecute(...) function to determine the appropriate command to execute. The conditions for which a command should be executed may depend on several factors such as the keyword or specific message content.
I'm thinking something like the following:
public interface ISmsCommand
{
bool CanExecute(string sender, string message);
string Execute(string sender, string message);
}
public class SmsHelpCommand : ISmsCommand
{
public bool CanExecute(string sender, string message)
{
return (message.ToLower().StartsWith("help"));
}
public string Execute(string sender, string message)
{
return "For more info, visit...";
}
}
public class SmsHttpHandler : IHttpHandler
{
List<ISmsCommand> _commands = new List<ISmsCommand>();
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
var sender = context.Request.Form[...];
var message = context.Request.Form["Message"];
foreach (var command in _commands)
{
if (command.CanExecute(sender, message))
{
var response = command.Execute(sender, message);
SendTextMessage(sender, response);
break;
}
}
}
}
Something about this code seems fishy to me, though. I think I don't like having to send the arguments to both the CanExecute function and the Execute function, but I'm not sure. Any thoughts?