Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^4: OO design: returning string and/or special value

by wanna_code_perl (Friar)
on Oct 07, 2019 at 22:31 UTC ( [id://11107174]=note: print w/replies, xml ) Need Help??


in reply to Re^3: OO design: returning string and/or special value
in thread OO design: returning string and/or special value

$obj->string / $obj->special was what I originally went with, and I may still do. I came here hoping for some hints on possibly simplifying it, though, as string is the 95% case. I rate the odds of the programmer forgetting to write my $special = $obj->method->special at least as high as forgetting to write my (undef, $special) = $obj->method</p>. Since both are strings (and strings are indeed the best option), both would silently use the "wrong" value if forgotten. <c>wantarray might actually be slightly superior, in that the two calling options look very different and errors would hence be easy to spot:

my $string = $obj->method; # vs. my $string = $obj->meth +od->string; my (undef, $special) = $obj->method; # vs. my $special = $obj->meth +od->special;

I'll give it some more thought though. Thanks for the input.

Replies are listed 'Best First'.
Re^5: OO design: returning string and/or special value
by AnomalousMonk (Archbishop) on Oct 07, 2019 at 23:52 UTC
    ... vast majority of the time, the caller is going to want that value in plain old string format.... sometimes they want both string and special formats from the same call ...

    How about just use good old wantarray to either:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "sub flexi { my ($str) = @_; ;; my ($string, $special) = map { uc, scalar reverse } $str; ;; return wantarray ? (string => $string, special => $special) : $string ; } ;; my %hash = flexi('foobar'); dd \%hash; ;; my $string = flexi('foobar'); dd $string; " { special => "raboof", string => "FOOBAR" } "FOOBAR"
    or:
    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "sub flexi { my ($str) = @_; ;; my ($string, $special) = map { uc, scalar reverse } $str; ;; return wantarray ? ($string, $special) : $string ; } ;; my $string1 = flexi('foobar'); dd $string1; ;; my ($string2, $special) = flexi('foobar'); dd $string2, $special; " "FOOBAR" ("FOOBAR", "raboof")


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11107174]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-04-19 12:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found