Skip to content

Commit

Permalink
Data class rule: removing several cases from the scope of the inspection
Browse files Browse the repository at this point in the history
### What's done:
- Removed annotation, value, sealed, inline, inner classes from the scope
- Added tests
  • Loading branch information
orchestr7 committed Jul 23, 2022
1 parent a50c713 commit 20b3e2c
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,10 @@ class DataClassesRule(configRules: List<RulesConfig>) : DiktatRule(
}

private fun handleClass(node: ASTNode) {
with((node.psi as KtClass)) {
if (isData() || isInterface()) {
return
}
if ((node.psi as KtClass).isDefinitelyNotADataClass()) {
return
}

if (node.canBeDataClass()) {
raiseWarn(node)
}
Expand Down Expand Up @@ -128,6 +127,12 @@ class DataClassesRule(configRules: List<RulesConfig>) : DiktatRule(
return true
}

/** we do not exclude inner classes and enums here as if they have no
* methods, then we definitely can refactor the code and make them data classes
**/
private fun KtClass.isDefinitelyNotDataClass() =
isValue() || isAnnotation() || isInterface() || isData() || isSealed() || isInline() || isInner()

@Suppress("UnsafeCallOnNullableType")
private fun areGoodAccessors(accessors: List<ASTNode>): Boolean {
accessors.forEach {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,58 @@ class DataClassesRuleWarnTest : LintTestBase(::DataClassesRule) {
)
}

@Test
@Tag(USE_DATA_CLASS)
fun `annotation classes bug`() {
lintMethod(
"""
|@Retention(AnnotationRetention.SOURCE)
|@Target(AnnotationTarget.CLASS)
|annotation class NavGraphDestination(
| val name: String = Defaults.NULL,
| val routePrefix: String = Defaults.NULL,
| val deepLink: Boolean = false,
|) {
| object Defaults {
| const val NULL = "@null"
| }
|}
""".trimMargin()
)
}

@Test
@Tag(USE_DATA_CLASS)
fun `value or inline classes bug`() {
lintMethod(
"""
|@JvmInline
|value class Password(private val s: String)
|val securePassword = Password("Don't try this in production")
""".trimMargin()
)
}

@Test
@Tag(USE_DATA_CLASS)
fun `sealed classes bug`() {
lintMethod(
"""
|sealed class Password(private val s: String)
""".trimMargin()
)
}

@Test
@Tag(USE_DATA_CLASS)
fun `inner classes bug`() {
lintMethod(
"""
|inner class Password(private val s: String)
""".trimMargin()
)
}

@Test
@Tag(USE_DATA_CLASS)
fun `shouldn't trigger on interface`() {
Expand Down

0 comments on commit 20b3e2c

Please sign in to comment.