https://kotlinlang.org logo
Title
f

Florian

08/22/2021, 12:04 PM
is it okay to shadow method arguments if I need a modified value like the progress here?
y

Youssef Shoaib [MOD]

08/22/2021, 12:42 PM
From what I can find online, it's kind of in the "you probably shouldn't be doing this, but if you are then it's fine" territory. Specifically, the discussions were about actually using
var
instead of
val
for shadowing, but it still should apply. For reference, https://discuss.kotlinlang.org/t/function-parameters-are-val-not-var/897/5?u=kyay10 and https://stackoverflow.com/questions/44109098/how-do-i-make-method-param-mutable-in-kotlin
f

Florian

08/22/2021, 1:09 PM
@Youssef Shoaib [MOD] thank you 👍
👍 1
j

Jakob Löhnertz

08/22/2021, 1:33 PM
I can only agree to what @Youssef Shoaib [MOD] said. I would avoid it but looking at your example, there's no obvious variable name that is nice. You can go for something like
finiteProgress
for the variable ofc, but well, it's quite clunky. What I would personally go for is that the either the parameter and/or the variable contains the unit (probably better the parameter, such that it is clear for the callers); is this a percentage, or some other scale? And then you can keep the variable name as is, because in the context of the function, it's probably quite clear.
e

edrd

08/22/2021, 1:42 PM
Would be bad if the two variables had very different meanings, but in this case it's a simple normalization, so it looks fine. However, I'd look into solving this with domain objects to avoid what is called "primitive obsession" (i.e. using primitives to represent high-level domain concepts). So instead of using
Float
you would have a
Progress
type:
@JvmInline
value class Progress(private val value: Float) {
  fun toFloat(): Float = if (value.isNaN()) 0f else value
}
(note: although there's the
toFloat
method, you should pass
Progress
around and only use it if necessary -- e.g. when calling libraries) This is nice because: 1. It moves the normalization logic out of your function, reducing complexity and making it reusable. 2. You can test it separately. 3. You can create extension functions for it without polluting
Float
namespace. 4. It has no overhead because of value classes (❤️) More on this here: https://blog.ploeh.dk/2015/01/19/from-primitive-obsession-to-domain-modelling/
🙌 1
f

Florian

08/22/2021, 3:44 PM
@Jakob Löhnertz The thing is, I actually want to avoid accidentally using the method argument in the method body
@edrd Looks like a really cool approach, I'll try that out!
🤘 1