Any suggestions for following problem, let's say I...
# announcements
j
Any suggestions for following problem, let's say I have a simple type which is used in two different projects A and B (modules). Now I need to make this same type behave different in module B. Code example:
Copy code
open class Name(name: String) : ValueType(name) {

    init {
        require(value.length <= 10) {
            "Name '$value' length exceeds the maximum value of 10"
        }
    }
}
For module B I need additional validation in init-block
Is there any way to achieve this by some kind of module specific condition/parameter or other way perhaps?
h
No, there's No such thing. Since it's an open class, you could add custom init blocks in the subclass in your submodule. But tbh i would not recommend that structure alltogether. The validation just seems to be sth you can not easily share or extend, so maybe it should not be part of the hierarchy. But i guess your classes are more complex, so removing that might not be pracitcal. You could accept a lambda in Name constructor that is executed in init with custom validation. But that makes your base class do arbitrary input validation that throws and is not reflected in the type system, which is not too nice.
Make your classes closed, extract validation to extension methods and call those in the init blocks of simple data classes. In module b you then do sth like init { validateLength(); validateOther() } and you are done. Validation is shared but explicitly called and composable because no hierarchy, just calls
j
Thanks for comments, I agree that validation should not be part of the hierarchy but in this project I'm afraid we are past that point where we can change it. What I did not mention is that these Name types are also used by interfaces which are shared by A and B. Also what you suggest I think we would end up in situation where we would have types like FirstNameA and FirstNameB ? Or maybe I misunderstood how extension functions would help here.
h
No i think you got ne right. When you have two classes Name, each in a module and they differ in for example validation, then why Not make Them two classes?:) foo.a.Name and foo.b.Name. each type guaranteeing that the domain specific validation has taken place. Yea y the hierarchy is the real problem, but hey that's known with hiearchies, isnt it :) implementation by Delegation could replace the current usages. First step would be to remove the hierarchy, use simple data classes and Delegation. Next step is replacing existing usage with those data classes. Don't think there's another option, since you can't remove validation from your base class it seems. Adding another layer to the hierarchy would be possible as well, accepting a validation lambda as said already, but that is not the best design all in all