Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

As implemented, your example would fail if the called in scalar context, as in $name = $object->name;, because wantarray will return false if you've called in scalar context. To check for void context, you need to check if the result of wantarray is undefined. This illustrates how easy it is to make a mistake with single get/set methods. Also, what if it is valid to set the name property to an empty string, the string '0' or undef? How would you do that with this combined get/set? Oh, you could play with wantarray to find out if you're getting, but what if (as is the case in the original, and common) the set method is to return the value set? Wantarray will be defined, so you have no way of reliably knowing if you were really called as get or set.

It is more readable, safer, and simpler to code:

sub set_name { my $self = shift; ## validation /untainting here ## $self->{name} = shift; return $self->{name}; } sub name { my $self = shift; if (@_) { warn "Attempt to set value in get" } return $self->{name}; }
<-radiant.matrix->
Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
The Code that can be seen is not the true Code
"In any sufficiently large group of people, most are idiots" - Kaa's Law

In reply to Re^2: Things I Don't Use in Perl by radiantmatrix
in thread Things I Don't Use in Perl by Ovid

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-04-24 08:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found