KeepCalmAndCarryOn
KeepCalmAndCarryOn

Reputation: 9075

Perl Moose Hash traits

I have a parameter object in Moose which has attributes of file wildcards to glob

So I had a method to do this

sub getInputFileParams{
    my ($self) = @_;

    #the only parameters passed in are in fact the input files
    return keys(%{$self->{extraParams}});
}

but then I though why not iterate the attributes as a hash?

has 'extraParams' => (
    is        => 'ro',
    isa       => 'JobParameters::Base',
    default   => sub { {} },
    traits    => ['Hash'],
    handles   => {
       keys_extraParams => 'keys',
    },

);

However that chokes as its not a hash reference. have I missed something or is using the object as a hash bad

Upvotes: 0

Views: 1420

Answers (2)

RickF
RickF

Reputation: 1822

You've got all tools in place in your Moose class definition, you just aren't using them - try this:

return $self->keys_extraParams

Upvotes: -1

t0m
t0m

Reputation: 136

Yes, using objects as plain hashes is bad.

You're accessing their internal state directly, which bypasses any interface that they may present and makes your class closely coupled to the internal representation of the JobParameters::Base class.

If you need to be able to get the contents of a JobParameters::Base object as a hash, then add a to_hash method to JobParameters::Base, and delegate to that method in your attribute...

This means that if later you add caching (for example!) to JobParameters::Base, and use a __cache key to store internal data, you can safely make this change by also changing the to_hash method to remove the internal data from the hash it returns.

It is fine to store an attribute as just a hash, but if you're storing a blessed hash, then don't reach into it's guts..

Upvotes: 5

Related Questions