Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Rule: UnnecessarySafeCall #2572

Closed
IlyaPavlovskii opened this issue Apr 3, 2020 · 3 comments
Closed

New Rule: UnnecessarySafeCall #2572

IlyaPavlovskii opened this issue Apr 3, 2020 · 3 comments

Comments

@IlyaPavlovskii
Copy link

IlyaPavlovskii commented Apr 3, 2020

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
@schalkms
Copy link
Member

schalkms commented Apr 3, 2020

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.

@cortinico
Copy link
Member

cortinico commented Apr 3, 2020

I actually already have this call implemented on one of my branch:
cortinico@d79e2b5

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 👍

@schalkms
Copy link
Member

schalkms commented Apr 3, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants