in reply to Please review my code: 100 Doors.
sub toggle_door { my $door_ref = shift; if( $$door_ref eq 'Closed' ) { $$door_ref = 'Open'; } else { $$door_ref = 'Closed'; } return $$door_ref; }
My own preference is to avoid if ... else ... or if ... elsif ... else ... vipers' nests if possible — and if you add another state or states (e.g., 'HalfClosed'), you'll have to add one or more elsif clauses. "But this application will never, ever require another state", you say. Famous last words.
The following is my preferred approach to something like this. Most of the heavy lifting is actually data validation. (The state keyword requires Perl version 5.10+.) The following is tested per your test plan:
sub toggle_door { my ($door_ref) = @_; state $transition = { qw(Open Closed Closed Open) }; $$door_ref // die 'undefined door state'; exists $transition->{$$door_ref} or die qq{unknown door state '$$door_ref'}; return $$door_ref = $transition->{$$door_ref}; }
At some sacrifice of self-documentation, $_[0] can be used in place of $$door_ref throughout the toggle_door() function, in which case the initial
my ($door_ref) = @_;
statement is not needed, and, important note, the function is called with no reference taken, e.g., toggle_door($doors[$i]);(also tested, but I'm not sure I would actually use this):
sub toggle_door { state $transition = { qw(Open Closed Closed Open) }; $_[0] // die 'undefined door state'; exists $transition->{$_[0]} or die qq{unknown door state '$_[0]'}; return $_[0] = $transition->{$_[0]}; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Please review my code: 100 Doors.
by lwicks (Friar) on Jul 03, 2013 at 08:01 UTC |