is there a better way to write this? (less verbose...
# getting-started
h
is there a better way to write this? (less verbose and less or equal impact)
Copy code
val height = points.maxBy(Point::y)!!.y - points.minBy(Point::y)!!.y
I often find myself using this schema
Copy code
val height = points.map(Point::y).run { max()!! - min()!! }
uses less characters but iterates an additional time through
points
of course if i really wanted to do it best by performance, i could accomplish this in only one iteration...
a
uses less characters but iterates an additional time through
points
Consider the implications of this statement; character count is not a metric you want to optimize for when the sacrifice is both runtime performance and clarity for the reader :)
2
h
yep!
i'm not certain that the second form is even more readable than the first
though i don't find the first as readable as what is happening is simple
a
you'd probably end up with code that's both more readable and performant if you factored this out into an extension function on
Iterable<Point>
and wrote the function as clearly as possible without the higher order function golf 🙂
h
yeah, in this case, i'm just going to go for performance, so i moved the init of
height
into
init
to be computed alongside
width
and some other values
a
Late reply but though I'd thrown in my two cents. I think there are a few considerations. First, if we're going the performance route, then it's imperative to understand the underlying algorithms of the applied language constructs. For me, if it's not performance critical, I use a different approach. I tend to let my eyes make the decision. I'm a visual thinker. So what I mean by the previous statement is if, when I'm scanning the code, I can "see" the logic then it's good enough. In your two examples, I would choose the first because I immediately see the logic. In the second, I have to think about it. That's probably why I tend to put if/else on four lines instead of two. My brain just "sees" it differently. Rather, It sees it faster. Hope that makes sense.
h
Good point. In that case, the best solution is undoubtedly @Adam Powell's assuming the method is intuitively named and written in the basics.