3 ms·
The idea that there's only one way implies that code context means nothing. For example, if you have a simple function that kicks backed cached values: sub
by alabamenhu 7y ago
The idea that there's only one way implies that code context means nothing.
For example, if you have a simple function that kicks backed cached values:
sub foo ($bar) {
if %cache{$bar}.defined {
return %cache{$bar}
}
}
Is an absolutely correct way of doing things. But it's messier then using a postfix:
sub foo ($bar) {
return %cache{$bar} if %cache{$bar}.defined
}
Or simplifying:
sub foo ($bar) {
return $_ with %cache{$bar}
}
While it's true that
sub foo ($bar) {
.return with %cache{$bar}
}
is possible, I don't tend to use it too much because the dot syntax isn't as pretty with postfixes ha. But each of these options has a place where it is the better option, but none of them is universally the one and only best option. Nested ifs with multiple statements may go better with the first one, but if several conditionals have similar elements and are simple statements it might behoove to line them up with whitespace. But the placement of return right at the outset (as opposed to nestled in an if statement) to me makes it clear the return value is a gate-keeper of sorts. Ditto for using 'die if [cond]' which much more in your face then 'if [cond] {die}'.
All of the above code is readable though. Of course, a functional approach could be just as valid and readable, and clear:
multi sub foo ($bar where %cache{$bar}.defined)
{ %cache{$bar} }
multi sub foo ($bar) { ... }
Or taking advantage of traits:
sub foo ($bar) is cached { ... }
Almost inevitably the unreadable code is where someone is trying intentionally to be cute and write unreadable code. But that can be done in languages like C too, or with any language that allows single letter variables.