https://kotlinlang.org logo
Title
f

Florian

12/29/2019, 8:45 AM
Which one do you like more? 2 is more concise but I don't really like the unnecessary else
2️⃣ 19
m

Matteo Mirk

12/29/2019, 8:52 AM
definitely the second one! But this doesn’t apply just to Kotlin, I also follow the same style in Java and other languages: unnecessary repetition creates noise and hinders readability.
Upon further reading your code, if you make those
BiometricManager
constants into an enum you won’t need an else branch. Turns out that you won’t need a “when” either, since the text matches the constant name:
val message = biometricManager.canAuthenticate().toString()
👆 2
1
f

Florian

12/29/2019, 9:20 AM
Thank you very much that makes sense
the text is just a placeholder but I didn't mention that
m

Matteo Mirk

12/29/2019, 10:09 AM
oh okay fine, then to match the text you can either use one of these: • when • enum with a “message” field • EnumMap
f

Florian

12/29/2019, 10:43 AM
But
BiometricManager
is a class of the Android system
m

Matteo Mirk

12/29/2019, 10:48 AM
No problem you can still use “when” or an EnumMap. Oh and don’t forget Kotlin has extension functions, so you could define an extension on BiometricManager to retrieve the message, maybe private only in the relevant scope
💯 1
f

Florian

12/29/2019, 2:32 PM
Thank you very much 👍
c

codeslubber

12/29/2019, 6:54 PM
Neither. Why not have a simple mapping if all you are doing is getting a message (enum)?
👍 1
h

Hullaballoonatic

01/01/2020, 8:48 PM
The first one is also more tedious in about every way. Say you needed to change the function acting on all the results. Copy/paste code is industry standard dirty code
1
d

Daniel

01/02/2020, 8:01 PM
when(...) {
  ... -> showToast.value = "Success"
  ... -> showToast.value = "Error"
}
showToast is a live data and the toast is shown by the view
If you want to keep it like now make a
showToast(message: String)
method instead
To be extra clean of course :
showToast.value = R.string.success
d

darkmoon_uk

03/21/2020, 1:15 PM
Please don't do [1], ever, I seem to spend half my life at work cleaning up these redundancy messes. Besides being redundant in both program space and screen space, these copy/paste affairs often cloud the intent of the code.
👍 1
Since often, the intent is that every branch should result in a message being displayed, but repeating the
Toast
in every branch then returning doesn't fully enforce this. Working with an uninititalised
message
first means the compiler will fail fast if you leave any branches uncovered e.g. in case you introduce a new enum value later on.