I have a function as shown below, I'm wondering if...
# codereview
t
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
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
I want to have a custom error message, because the single error only gives a count, not the actual items listed.
d
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
aaah, nice 🙂
adapted this to my production code: 20 lines to 10 lines, and easier to understand
thank you @Dominaezzz!
d
No problem!
e
ps: you can even avoid the function body and the
return