rspec/rules/S6512/kotlin/rule.adoc

78 lines
2.0 KiB
Plaintext

== Why is this an issue?
Kotlin supports getters and setters for properties.
Because this is a built-in language feature, it should be the idiom used
to implement the getter and setter pattern instead of using custom idioms.
=== What is the potential impact?
==== Readability and Understanding
This change makes it easier to understand the code
because this is how delegation is to be used in Kotlin.
When developers share common standards and idioms, they need to spend less effort understanding each other's code.
==== Code Redundancy
Using a built-in language feature or a standard API is always better than a custom implementation,
because the reimplementation of something that already exists is unnecessary.
== How to fix it
Replace explicit functions that serve as getters and setters with property getters and setters.
=== Code examples
==== Noncompliant code example
[source,kotlin,diff-id=1,diff-type=noncompliant]
----
internal class GettersSetters {
private val length = 100
private var index: Int = 0
private var finished: Boolean = false
fun getIndex(): Int { // Noncomplient, use property getter
return min(max(0 ,index), length)
}
fun setIndex(value: Int) { // Noncompliant, use property setter
seek(value)
index = value
finished = value >= length
}
fun isFinished(): Boolean { // Noncomplient, use property getter
return finished
}
}
----
==== Compliant solution
[source,kotlin,diff-id=1,diff-type=compliant]
----
internal class GettersSetters {
private val length = 100
private var _index: Int = 0
private var _finished: Boolean = false
var index: Int // Compliant
get() = min(max(0 ,index), length)
set(value: Int) {
seek(value)
_index = value
_finished = value >= length
}
val finished: Boolean // Compliant
get() = _finished
}
----
== Resources
=== Documentation
* https://kotlinlang.org/docs/properties.html#getters-and-setters[Kotlin Docs, Getters and setters]