I find myself writing a lot of repetitive code lik...
# naming
m
I find myself writing a lot of repetitive code like this:
Copy code
return try {
    // ...
} catch (e: Exception) {
    handleError(e)
}
in some classes that have similar purposes. so, I decided to extract that block into a separate function called something like
runCatching
Copy code
return runCatching { ... }
but the problem is that it would be easily confused with the standard
kotlin.runCatching
, and I'm not using
kotlin.Result
either. so, I want a good name for that function but I can't think of any name other than
runCatching
. Any better ideas?
k
runHandlingError
?
r
I quite like
return withErrorHandling { ... }
m
@Kevin Del Castillo I guess it is a good one, at least it is better than
runCatching
because it would eliminate confusion.
@Rob Elliot this would be a good one too, but, I guess I would prefer with
run
@Rob Elliot this would be a good one too, but I guess I would prefer
run
prefixed one because it has more of a semantic meaning of what I'm doing inside those lambdas
r
I guess it's more idiomatic given the existing
run
prefixed methods, but perhaps because of the semantics of
java.lang.Runnable
I always expect
run
to mean something that returns
Unit
.
k
@Rob Elliot the only version of
run
that returns
Unit
is one that takes no parameters. In contrast to
Runnable.run()
, Kotlin has two commonly used versions of
run
in its own stdlib, both of which return the result of a given block. So I think it's idiomatic to expect
run
to return something. On the other hand, I would prefer your
withErrorHandling
suggestion. In Kotlin,
with
is also a function that returns the result of a given block. Just like
run
. So there's no reason for the OP to prefer a function prefixed with
run
instead of
with
.
r
I thought that was basically what I was acknowledging.
k
runWithErrorHandling
then (?) 😆 K
r
Since it's essentially a wrapper around
handleError
, I would use the same name.
Copy code
return handleError { ... }
Not sure if that's particularly idiomatic, but it's what makes sense to me.
m
@Ruckus this basically means to me that in all cases the code inside the lambda would always throw an exception, and this is not true, so I wouldn't say this is a good name
@Klitos Kyriacou @Rob Elliot I think
with
would also align with
kotlin.with
that shares (to some extent) the same purpose of the function I'm trying to create, so, I think this is the best option here
e
Personally, "with" brings to my mind a lambda with a receiver
r
I sometimes use variants of
safe
for this pattern.