arrow-left arrow-right brightness-2 chevron-left chevron-right circle-half-full facebook-box facebook loader magnify menu-down rss-box star twitter-box twitter white-balance-sunny window-close
Object-Oriented Tricks: #4 Starter Pattern
2 min read

Object-Oriented Tricks: #4 Starter Pattern

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.

Intent intent = new Intent(context, TargetActivity.class)
intent .putExtra(TARGET_NUMBER, 5);

intent .putExtra(TARGET_STRING, ‘test'");
startActivity(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:

/**
* Displays the Target screen
* Required extras:
* - int: TARGET_NUMBER
* - String: TARGET_STRING
*/
public class TargetActivity extends Activity {...}

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.

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:

public class TargetActvity extends Activity {

    public static void start(Context context, int targetNumber, String targetString) {
        Intent starter = new Intent(context, TargetActivity.class) ;
        starter.putExtra(TARGET_NUMBER, targetNumber) ;
        starter.putExtra(TARGET_STRING, targetString) ;
        context.startActivity(starter) ;
    }   

    @Override
    protected void onCreate(Bundle savedInstanceState) {...}
}

Android Studio also has a built-in live template for the starter:

live

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 (edit: bad metric) over the period of 3 years. I hope this helps you too.