in reply to Re: Re: Complex dispatch table
in thread Complex dispatch table
Semantics means "meaning", more or less. The semantics of a statement are going to be what it actually does. The syntax is just how the statement is structured. So you have to think about how the commands you are using are related. Perhaps some commands have a context (a "state"). Some commands might be "like" others (so you can use inheritance to specify their semantics: derive behaviour from a base class, modify it in the child class). Et cetera.
At the moment, you are basically assuming "all commands are semantically different" - they each get their own subroutine or module method call. You're also assuming "all commands are syntactically the same", but only in that they can be parsed by regexes. You could increase the level of syntactic sameness, and this might save you time typing out different regexes and format messages.
Here's a rough example:
package main; # ... my $command; eval { $command = CommandFactory->create ($input_string); # returns the r +ight subclass of Command }; #trap non-existent commands if ($@) {printandprompt("command not recognized");} if ($command->parse_syntax) { # check for syntax errors eval { $command->execute; }; # trap semantic errors, e.g. "user doesn't exist" if ($@) { print $@; # maybe die if need be } } else { printandprompt $command->syntax_string; } package CommandFactory; sub create { my $class = shift; my $str = shift; my ($cmd, @args) = split $str; my $cmd_class = "Command::" . ucfirst ($cmd); return $cmd_class->new(@args); } package Command; use vars qw/$SYNTAX/; # ... sub new { my $class = shift; my @args = @_; my $self = {args => \@args}; bless $self, $class; } sub _syntax { my $self = shift; no strict 'refs'; my $class = ref ($self) || $self; return ${"$class::SYNTAX"}; } sub parse_syntax { my $self = shift; # check $self->{args} against $self->_syntax # then parse the arguments into $self fields # return false on error # alternatively "die" and catch the exception } package Command::Msg; use Command; use base 'Command'; use vars qw/$SYNTAX/; $SYNTAX = { options => { player => { required => 1, arg => 'string', } loudness => { required => 0, arg => 'int' } } arguments => { min => 1, } }; sub execute { my $self = shift; # send $self->{msg} to $self->{player} with $self->{loudness} }
dave hj~
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Re: Complex dispatch table
by castaway (Parson) on Feb 20, 2003 at 13:05 UTC |