https://kotlinlang.org logo
#codereview
Title
# codereview
t

twisterrob

07/21/2019, 1:26 PM
I have a function as shown below, I'm wondering if there's a better way to express this (focusing on `if`/`else`/`return`/`throw` structure):
Copy code
private fun findTheField(fields: List<Field>): Field? {
	if (fields.isEmpty()) {
		return null
	}
	if (fields.size == 1) {
		return fields.first()
	}
	val selectedFields = fields.filter(::someCondition)
	if (selectedFields.size == 1) {
		return selectedFields[0]
	} else {
		throw IllegalArgumentException(
			"Too many fields matching some condition found: ${fields.joinToString(", ")}"
		)
	}
}
this question was triggered by Detekt:
ReturnCount
"... has 3 return statements which exceeds the limit of 2", which kind of has a point there.
d

Dominaezzz

07/21/2019, 1:31 PM
Copy code
private fun findTheField(fields: List<Field>): Field? {
    if (fields.isEmpty()) {
        return null
    }
    if (fields.size == 1) {
        return fields.first()
    }
    return fields.single(::someCondition)
}
t

twisterrob

07/21/2019, 1:32 PM
I want to have a custom error message, because the single error only gives a count, not the actual items listed.
d

Dominaezzz

07/21/2019, 1:33 PM
Copy code
private fun findTheField(fields: List<Field>): Field? {
    return when {
        fields.isEmpty() -> null
        fields.size == 1 -> fields.first()
        else -> fields.singleOrNull(::someCondition) ?: throw .....
    }
}
t

twisterrob

07/21/2019, 1:33 PM
aaah, nice 🙂
adapted this to my production code: 20 lines to 10 lines, and easier to understand
thank you @Dominaezzz!
d

Dominaezzz

07/21/2019, 1:48 PM
No problem!
e

elect

07/22/2019, 9:01 AM
ps: you can even avoid the function body and the
return