In a small set of classes for modeling chess situations, I wanted to build a class to represent positions. But I wanted to create (and export) only the valid 64 positions and make the constructor private after this to prevent the system from creating multiple objects for the same position. Basically a singleton, but with 1 = 64. A 64-ton. Kind of.
Possible usage:
use Positions; # exports positions
my $pos = e4;
# something happens...
do_foo() if $pos == d5;
do_bar() if $pos->row == 8;
My solution works the way I want but it feels kind of inelegant and over-designed.
Basics:
package Position;
use Moo;
has column => (is => 'ro');
has row => (is => 'ro');
has name => (is => 'lazy');
sub _build_name {
my $self = shift;
return $self->column . $self->row;
}
sub to_string { shift->name }
# ...
There’s no error check for valid columns or rows with isa because I don’t want the class user to instantiate position objects at all. Now to the exporting:
# prepare 64 positions
my %position;
foreach my $col ('a' .. 'h') {
foreach my $row (1 .. 8) {
# build
my $name = "$col$row";
my $pos = Cherl::Position->new(column => $col, row => $row);
# remember
$position{$name} = $pos;
}
}
# export
sub import {
my $class = shift;
my $caller = caller;
# magic!
no strict 'refs';
for my $name (sort keys %position) {
*{$caller . '::' . $name} = sub { $position{$name} };
}
}
# make it private
sub BUILDARGS {
my ($class, @args) = @_;
die 'private' unless +(caller 1)[0] eq __PACKAGE__;
return $class->SUPER::BUILDARGS(@args);
}
The alternative I could think of
would be to add an error check for columns and rows and overload the == operator to return true if two position’s names are equal to compare positions properly. I’m a little bit scared to build a big number of objects for the same position in this scenario, but maybe this is early optimization.
So the question is if there’s a better way to design this class (using Moo). TIA! 🙂
I would probably have a Create() method (instead of new X…), with code inside Create() so it will only create the legal positions. You could even make it return the current position object for that position if you tried to call Create() again on that position.
Also, you might even make the actual position class a hidden child class of the Create()-ing class if you are worried about accidentally directly creating position objects.