Other than switching to something more OOish with fewer direct values accesses and more method calls, I fail to see what this example accomplishes.
The cons, though, are clear to me. You're using more vertical space in the editor. You're making more context switches. You're using more overall code, so there are more places for bug to get in (although the code is really simple).
Earlier in this series you posted a node about Fowler saying to replace temporary variables with inline expressions or something similar, didn't you? How's this:
sub get_price{
my $self = shift;
return (
( $self->{_quantity} * $self->{_item_price} ) > 1000
? ( $self->{_quantity} * $self->{_item_price} ) * 0.95
: ( $self->{_quantity} * $self->{_item_price} ) * 0.98
);
}
Of course, that's less legible, more bug prone, and trades one scalar (the memory for which could be reused once this little snippet goes out of scope) for having to recalculate the value twice, but it follows guru advice.
If you just do away with one of the two temps and use a more powerful operator, though:
sub get_price{
my $self = shift;
my $base_price = $self->{_quantity} * $self->{_item_price};
return $base_price *= $self->{_quantity} > 1000 ? 0.95 : 0.98;
}
That seems to me to be about the best compromise. You get rid of half your temporary values, it's still just one method, it's short, it's clear, and it's idiomatic.
Of course, there's still the small matter of three magic numbers, but for the example we can probably overlook that.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.