You are currently viewing What’s the most kotlin way to make a contract that a property of a class will get supplied by its creator?

What’s the most kotlin way to make a contract that a property of a class will get supplied by its creator?

I’m in the middle of refactoring a large project. Everything works the way that I want it to, but I’m trying to push myself abstract using patterns and do a better job of making classes easy to understand at the site where they are used instead of inside the class itself.

And I’m noticing a really common pattern in my first implementation. About 40 or 50 times, I’ll create a custom view whose properties will all be supplied (or modified) by a parent at some later time. So it looks like this:

class ChildWhoWillGetUsedLater(context:Context):ConstraintLayout(context){ var textView:TextView lateinit var parentProvidesMe:Int init{ inflate(//inflate the view) textView=findViewById(//get the view) doSomeCustomStuff() } fun doSomeCustomStuff(){//do stuff} } 

And then at some later date, when it’s time for the parent to work its magic, this happens:

class Parent()://Probably some sort of Activity or Fragment{ ... ... theChildINeed=ChildWhoWillGetUsedLater(context) theChildINeed.textView.text="My parent is supplying this" theChildINeed.parentProvidesMe=5 ... ... } 

See that kind of workflow works great if you’re one guy and you know where everything goes and you’re writing the parent and the child at the same time. But if it’s way off 5 years in the future and there are a team of people working together, then ideally the child should communicate more at the site of invocation inside of parent exactly what the parent’s responsibilities are. Like if that lateinit var doesn’t get supplied by parent, it could be really confusing for other people who weren’t there when I wrote it.

I know abstract classes are good for expressing responsibilities of what an instantiator is required to supply. So maybe I could make ChildWhoWillGetUsedLater abstract and then make the lateinit var abstract. Is that the way to do it?

I guess what I’m asking is, how can I signal to the linter in the IDE that the parent has a responsibility to supply things to the child so that in the future, people don’t have to learn about the child by directly reading the child class?

submitted by /u/arnoldfrend
[link] [comments]