Created
February 21, 2010 21:36
-
-
Save brunoV/310560 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use perl5i::latest; | |
use Test::More; | |
{ | |
package Object; | |
use Data::Dumper::Concise; | |
use Digest::MD5 qw(md5_hex); | |
sub new { | |
my ($class, $args) = @_; | |
bless { %$args } => $class; | |
} | |
sub as_string { | |
my $self = shift; | |
# Stringified contents + memory adress = uniqueness? | |
return Dumper($self) . "$self"; | |
} | |
sub id { | |
my $self = shift; | |
my $id = md5_hex( $self->as_string ); | |
} | |
} | |
my $pepe = Object->new( { name => 'pepe', age => 42 } ); | |
my $evil_twin = Object->new( { name => 'pepe', age => 42 } ); | |
my $rosa = Object->new( { name => 'rosa', age => 34 } ); | |
isnt( $pepe->id, $rosa->id ); | |
isnt( $pepe->id, $evil_twin->id ); | |
$pepe = Object->new( { can => sub { 'dance' } } ); | |
$rosa = Object->new( { can => sub { 'paint' } } ); | |
isnt( $pepe->id, $rosa->id ); | |
my $copy = $pepe; | |
is( $pepe->id, $copy->id ); | |
done_testing(); | |
__END__ | |
All tests pass. However, if objects are mutable, the id changes. | |
Don't know if this is desirable or not. If it's not, a solution | |
would be to lazily compute the id and cache it in some sort of | |
global hash, so that mutation of the object doesn't change the | |
object's id. And actually, in that case we could just use UUID's | |
since the contents of the object are not related to the id in any | |
way. | |
Update: Ok, I checked ruby's behavior. the id changes when the | |
content changes, so an approach similar to the one showed here | |
might do the trick. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment