Detekt: New Rule: UnnecessarySafeCall

Created on 3 Apr 2020  路  3Comments  路  Source: detekt/detekt

Expected Behavior of the rule

I would like to be able to detect unnecessary safe call like:

val notNullValue = "some-label"
val length1 = notNullValue?.length
val length2 = requireNotNull(notNullValue).length
val length3 = checkNotNull(notNullValue).length

Context

This rule will be helpful with refactoring code and improves code performance.
For example:

// Before changes
val someValue: String? = null
val length = someValue?.length 

// After refactoring
val someValue: String = DEFAULT_VALUE
val length = someValue?.length // ? the safe call still here, 
// but should be better to remove this operator
feature rules

Most helpful comment

~I actually already have this call implemented on one of my branch:
https://github.com/cortinico/detekt/commit/d79e2b55dd22c14ea2741a016ce1b23f6f815ba7~
~I'd love to clean it up a bit and propose a PR @schalkms~

EDIT: I do have a similar rule actually (detects unnecessary usage of !! rather than ?). I'll pick this up anyway 馃憤

All 3 comments

Good idea! We always welcome new ideas.

This rule will be helpful with refactoring code and improves code performance.

Not necessarily does it improve performance, since the optimizer in the compiler suite checks this cases and doesn't generate the corresponding bytecode for the if (foo != null) foo.bar() statement.

~I actually already have this call implemented on one of my branch:
https://github.com/cortinico/detekt/commit/d79e2b55dd22c14ea2741a016ce1b23f6f815ba7~
~I'd love to clean it up a bit and propose a PR @schalkms~

EDIT: I do have a similar rule actually (detects unnecessary usage of !! rather than ?). I'll pick this up anyway 馃憤

I think both rules are valuable for detekt. Thanks @cortinico ! That's awesome. Do you also submit a PR for the UnnecessaryNotNullOperators rule? That would be great.

Was this page helpful?
0 / 5 - 0 ratings