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

thuytrinh

06/02/2020, 2:34 PM
Hi everyone, I’m sorry if this has been discussed already somewhere. I’m trying to get the benefit of the
ThrowsCount
rule. I have a violated code here:
Copy code
private fun ensureScanningIsPossible() {
    if (!isDiscoveryPermissionGranted) {
        throw DiscoveryErrors.DiscoveryPermissionsMissingError(neededDiscoveryPermissions)
    } else if (isDiscoveryOngoing) {
        throw DiscoveryErrors.DiscoveryAlreadyStarted
    } else if (!isBluetoothAvailable()) {
        throw DiscoveryErrors.BluetoothDisabledError
    } // More to come later...
}
Why is this discouraged? The doc said: “Functions should have clear 
throw
 statements”. How can we achieve a “clear” version? I tried to refactor by using nullable type but I feel a bit skeptical about the new code:
Copy code
private fun ensureScanningIsPossible() {
    val error: DiscoveryErrors? = when {
        !isDiscoveryPermissionGranted -> DiscoveryErrors.DiscoveryPermissionsMissingError(neededDiscoveryPermissions)
        isDiscoveryOngoing -> DiscoveryErrors.DiscoveryAlreadyStarted
        !isBluetoothAvailable() -> DiscoveryErrors.BluetoothDisabledError
        else -> null
    }
    error?.let { throw it }
}
g

gammax

06/02/2020, 2:38 PM
To give you a general answer, exceptions are generally discouraged in Kotlin. This goes along with the
ThrowsCount
rule that should limit the usages of the
throw
keyword (and so reducing usages of exceptions). In your specific case, the first snippet you posted is definitely better than the second and you should probably just suppress the rule violation for your function.
Or you can raise the
ThrowsCount
threshold a bit
👍 1
v

Venkat , Bangalore , India

06/02/2020, 2:39 PM
@thuytrinh can u paste ur detekt config ThrowsCount here
Copy code
ThrowsCount:
  active: true
  max: 2
something like this
i believe the ThrowsCount is activated
t

thuytrinh

06/02/2020, 2:39 PM
That’s the exact config I’m using. The default one.
v

Venkat , Bangalore , India

06/02/2020, 2:40 PM
just to reproduce ur issue i added like below and detekt found this
Copy code
private fun ensureScanningIsPossible() {
    if (!false) {
        throw NullPointerException()
    } else if (true) {
        throw throw NullPointerException()
    } else if (!false) {
        throw throw NullPointerException()
    } // More to come later...
}
t

thuytrinh

06/02/2020, 2:40 PM
i believe the ThrowsCount is activated
Right. I’m aware of it. Just wanna understand the benefit of it as well as how to refactor
v

Venkat , Bangalore , India

06/02/2020, 2:40 PM
style - 10min debt ThrowsCount - [ensureScanningIsPossible] at
@thuytrinh got ur point.. misunderstood mate
👌 1
@thuytrinh irrespective of throwcount over here, this style of more if/else leads to Codesmell:Switch https://refactoring.guru/smells/switch-statements
☝️ 1
4 Views