ArchUnit icon indicating copy to clipboard operation
ArchUnit copied to clipboard

Feature request: Support validating only private setters in Kotlin

Open rvplauborg opened this issue 4 years ago • 1 comments

Hi,

Say we have a Kotlin class with a property

var someProp: String = ""
    private set
var otherProp: String = ""
    private set

Unless I missed something, it is not currently possible to test this is the case. haveOnlyFinalFields does not fit, as we want to test that we only have properties that have private setters.

rvplauborg avatar Oct 20 '21 14:10 rvplauborg

Correct me if I'm wrong, but can't you simply do something like

@ArchTest
val `classes should have only private setters`: ArchRule =
    classes().should(haveOnlyPrivateSetters())

private fun haveOnlyPrivateSetters() = object : ArchCondition<JavaClass>("have only private setters") {
    override fun check(item: JavaClass, events: ConditionEvents) {
        item.methods
            .filter { it.name.startsWith("set") }
            .filter { !it.modifiers.contains(JavaModifier.PRIVATE) }
            .forEach { events.add(SimpleConditionEvent.violated(item, "Setter ${it.name}(..) is not private")) }
    }
}

I mean, possibly a little more sophisticated, like also checking the 4th char is upper case and there is a backing field, but theoretically with something like this it is possible?

codecholeric avatar Oct 24 '21 18:10 codecholeric