https://kotlinlang.org logo
#konsist
Title
# konsist
p

PoisonedYouth

09/21/2023, 12:02 PM
Is it possible to assert, that all classes of a package (that contains Spring components) only depend on abstractions (Interface) and not concrete implementation? Something like below:
Copy code
Konsist.scopeFromProduction(moduleName = module)
            .classes()
            .withPackage("com.poisonedyouth.example.adapter..")
            .assert {
                it.primaryConstructor!!.parameters.all { parameter ->
                    // Check that it is only an interface type
                }
            }
n

Natalia Peterwas

09/21/2023, 12:25 PM
I’m afraid Konsist doesn’t have a perfect solution for this case yet and it can only be done with a trick like below:
Copy code
val interfaces = Konsist
            .scopeFromProduction()
            .interfaces()
            .map { it.name }

        Konsist.scopeFromProduction()
            .classes()
            .withPackage("com.poisonedyouth.example.adapter..")
            .assert {
                it.primaryConstructor!!.parameters.all { parameter ->
                    parameter.hasType { type ->
                        interfaces.any { interfaceName ->
                            type.sourceType == interfaceName
                        }
                    }
                }
            }
But we have a ticket to add a “complex references” - types will return actual instance of KoDeclaration, not a string. This will give is way to check if given type is class or an interface. ATM it may be hard to achieve.
p

PoisonedYouth

09/21/2023, 12:37 PM
Thanks that is working for the moment for me 🙂
❤️ 1
i

igor.wojda

09/21/2023, 8:00 PM
We have better implementation of parents in our backlog - idea is for parents to return actual KoDeclaration, so you will be able to determine if it is class/interface and you will be able to get from parent all members, annotations, etc. BTW @PoisonedYouth I see you are a Spring dev 🙂 Heaving limited Spring experience we are looking for more inspirations regarding Konsist usage in the Spring domain. The above test is not the best one as it is using "hack", but if you think you have some good examples please or just update this snippet https://github.com/LemonAppDev/konsist-documentation/blob/main/inspiration/snippets/spring-snippets.md or share them with us. We are looking for and relatively simple tests, that could be helpful for the Spring community by addressing common pain points and would inspire devs to try Konsist.
p

PoisonedYouth

09/22/2023, 6:11 AM
I switched my existing ArchUnit tests to Konsist, these are mainly architectural tests. I just now starting to evaluate if I can use Konsist to further add constraints to the code base (like the above one - only injecting abstractions instead of concrete implementations). As soon as I find helpful and generic snippets that maybe helpful for other I will update them to the snippet area.
❤️ 1
2 Views