paint-brush
Object Oriented Tricks: #4 Starter Pattern -Android Editionby@arunsasidharan
9,700 reads
9,700 reads

Object Oriented Tricks: #4 Starter Pattern -Android Edition

by Arun SasidharanApril 29th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<a href="https://hackernoon.com/tagged/oot" target="_blank">OOT</a> is a mini series on writing maintainable <a href="https://hackernoon.com/tagged/object-oriented" target="_blank">Object Oriented</a> code without pulling your hair out. Click here for <a href="https://hackernoon.com/oo-tricks-the-art-of-command-query-separation-9343e50a3de0" target="_blank">trick #1</a>, <a href="https://hackernoon.com/object-oriented-tricks-2-law-of-demeter-4ecc9becad85" target="_blank">trick #2</a>, <a href="https://hackernoon.com/object-oriented-tricks-3-death-by-arguments-d070ac86d996" target="_blank">trick #3</a>.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Object Oriented Tricks: #4 Starter Pattern -Android Edition
Arun Sasidharan HackerNoon profile picture

OOT is a mini series on writing maintainable Object Oriented code without pulling your hair out. Click here for trick #1, trick #2, trick #3.

Construction

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 Intent .

DRY

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 grows, 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.

Static Starter

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:

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.

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: Twitter.

Check out the next trick here.

If you liked this post, please hit the little heart! ❤