The thing is, if you have advertized that you can put a scalar in and retrieve the same scalar, you've just set in stone that, fundamentally, you've got a scalar variable. Go ahead and make it one, and let the user treat it like one. Same for an array or even a hash. If it's a settable-gettable, it's a variable and should be advertized as one.
Here's the magic in the meditation: if it's not an ordinary version of whatever data type, you can tie — and thus encapsulate — it. (Update:) This is not to say that it's always the Right Thing To Do. If you need validation performed for each store, you would have to have a separate flag to indicate error, and it would be cumbersome for the programmer. But for values that the user is free to manipulate (and especially for those that he will often update), it can be a significant improvement in convenience.
Here's some silly code to illustrate. The "password" is stored in an encrypted form in memory (presumably as a cartoonishly misguided attempt to be more secure).
package Password; use Carp; use strict; my $security = 'reallysecure'; sub TIESCALAR { my $class = shift; my $arg; return bless \$arg, $class; } sub FETCH { my $self = shift; confess "wrong type" unless ref $self; croak "usage error" if @_; return substr($$self ^ $security, 0, length($$self)); } sub STORE { my $self = shift; confess "wrong type" unless ref $self; my $newval = shift; croak "usage error" if @_; if (length($newval) < 5) { carp "Not long enough" } elsif (length($newval) > 12) { carp "Too long" } else { $$self = substr($newval ^ $security, 0, length($newval)); # print "Stored ", join('.', unpack('H2'x length($$self), $$self)), + "\n"; # print "Plain is ", join('.', unpack('H2'x length($$self), $newval +)), "\n"; } } sub encoded_form { my $self = shift; $$self; } package Main; my $foo; # This would be my object my $pwref = tie $foo->{'bar'}, 'Password'; $foo->{'bar'} = 'squamous'; print $foo->{'bar'}, "\n"; $foo->{'bar'} =~ s/am/a1m/; print $foo->{'bar'}, "\n"; print "Encoded form is ", $pwref->encoded_form, "\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Encapsulation without methods
by Zaxo (Archbishop) on Jun 22, 2004 at 04:02 UTC | |
by Roy Johnson (Monsignor) on Jun 22, 2004 at 16:03 UTC | |
by Plankton (Vicar) on Jun 23, 2004 at 07:03 UTC | |
|
Re: Encapsulation without methods
by stvn (Monsignor) on Jun 22, 2004 at 02:40 UTC | |
by Roy Johnson (Monsignor) on Jun 22, 2004 at 03:45 UTC | |
by stvn (Monsignor) on Jun 22, 2004 at 04:33 UTC | |
|
Re: Encapsulation without methods
by dragonchild (Archbishop) on Jun 22, 2004 at 02:19 UTC | |
by Roy Johnson (Monsignor) on Jun 22, 2004 at 03:41 UTC | |
|
Benchmark: Encapsulation without methods
by Roy Johnson (Monsignor) on Jun 23, 2004 at 15:22 UTC |