What's the best way to shorten this code ? All cal...
# getting-started
s
What's the best way to shorten this code ? All call() methods take and return a list. Is there a way to chain all these operations ?
Copy code
var list = serviceA.call(list)
list = serviceB.call(list)
list = serviceC.call(list)
list = serviceD.call(list)
k
Make an extension function on the list type that takes a service as a parameter, it could become
Copy code
list.call(serviceA).call(serviceB).call(serviceC).call(serviceD)
think smart 1
c
If they’re all of the same interface, you can do a
.fold
operation
Copy code
listOf(
    serviceA,
    serviceB,
    serviceC,
    serviceD,
).fold(initial = emptyList()) { acc, service -> service.call(acc) }
k
Casey's idea is great, but it's funny how we consider it a "shortening" when 4 lines get "shortened" to 6 lines.
k
What Kevin Healy suggests could also work, only if your services all share the same interface with the
call
function that receives a list
k
@Kevin Del Castillo if they don't share the same interface, it could also work, by overloading the
call
function.
k
That would require four different overloads 😛
It kinda defies the purpose of shortening the code by adding more hidden code
1
k
mm, I dunno. I'd rather have more verbose code behind an API that enables more fluent code at the call site
c
Shortening doesn’t always mean fewer lines of code, but rather shortening the amount of thought needed to understand it. Even though I broke the
listOf()
down to multiple lines, it’s still only 1 statement which is easily understandable. I tend to break these kinds of lists down because I use IntelliJ’s “duplicate line” feature a lot, and this makes it easier Really, the snippet is just 1 “line”, or 1 “statement”. The
listOf()
is just boilerplate, those services could be injected via DI as a list so that wouldn’t necessarily actually be at the point where you do the sequence of
.call
. So my snippet reduces 4 statements down to 1, but it does require that one understands what the
.fold
operation is doing to actually make it more understandable
☝️ 1
k
@Kevin Healy Yeah that depends if the API you're building is meant to be used by a sufficient amount of developers for it to be considered a "public API", medium to big teams would benefit from this as well as library consumers if it's part of a library
k
I know it's not always practical, but I think it's good practice to write everything as though it might become a public API even if you're the sole developer; you never know who's going to pick up your code next
☝️ 1
k
Agree! I think it all boils down to a constant battle between idealism and pragmatism K
💯 1
c
Another flavour of this i’ve used is:
Copy code
val newList = list
        .let { serviceA.call(it) }
        .let { serviceB.call(it) }
        .let { serviceC.call(it) }
        .let { serviceD.call(it) }
👍 1