thuytrinh
06/02/2020, 2:34 PMThrowsCount
rule. I have a violated code here:
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:
private fun ensureScanningIsPossible() {
val error: DiscoveryErrors? = when {
!isDiscoveryPermissionGranted -> DiscoveryErrors.DiscoveryPermissionsMissingError(neededDiscoveryPermissions)
isDiscoveryOngoing -> DiscoveryErrors.DiscoveryAlreadyStarted
!isBluetoothAvailable() -> DiscoveryErrors.BluetoothDisabledError
else -> null
}
error?.let { throw it }
}
gammax
06/02/2020, 2:38 PMThrowsCount
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.ThrowsCount
threshold a bitVenkat , Bangalore , India
06/02/2020, 2:39 PMThrowsCount:
active: true
max: 2
thuytrinh
06/02/2020, 2:39 PMVenkat , Bangalore , India
06/02/2020, 2:40 PMprivate fun ensureScanningIsPossible() {
if (!false) {
throw NullPointerException()
} else if (true) {
throw throw NullPointerException()
} else if (!false) {
throw throw NullPointerException()
} // More to come later...
}
thuytrinh
06/02/2020, 2:40 PMi believe the ThrowsCount is activatedRight. I’m aware of it. Just wanna understand the benefit of it as well as how to refactor
Venkat , Bangalore , India
06/02/2020, 2:40 PM