We usually construct our objects in one place. It could be a constructor, builder, static factory method, abstract factory or any of the other Creational Patterns.
There are times when objects created by a framework need some additional state that we need to set. Once such example, in Android, is the
Activity class. The Activity is created by the Android framework and we can only add attributes via an
For the longest time, while starting Activities and adding extras, I used to add a comment on top of the Activity class mentioning all the extras that were required to start the Activity properly. Something like:
To me, such comments were good documentation. I had to start this
TargetActivity from various entry-points across many classes and had
startActivity(intent) written everywhere. This violated DRY: Don’t Repeat Yourself.
As the team and codebase grow, a lot of things could happen to this class:
- More extras get added.
- Comments go out of sync with the additional extras.
- Your team may forget to pass certain extras.
- You may forget to add the new extras to older calls.
To avoid disappointment at runtime, it’s nice to define a contract within the target class itself. Use a static starter method for this:
Android Studio also has a built-in live template for the starter:
I call this the Starter Pattern(?) for the lack of a better name. Please do let me know if there’s a name for this.
This helped me avoid a lot of confusion maintaining a project with about 150,000 lines of code over the period of 3 years. I hope this helps you too.
Originally posted on Medium