SOLID Intentions

Jon Finerty
WorldRemit
Published in
2 min readMay 26, 2018

Intents are a fundamental building block of Android apps¹. They are the mechanism with which you move a user from screen to screen, specifying both the destination and any data or parameters it might require.

To implement MainActivity I had to dig around in HelpActivity.java to see just what extras it required

So what can we improve here? For a start, the caller needs to know about the intent extra name, the type of value it takes and what combinations of extras are valid. None of which is strongly typed. Is user id required or just optional? Better look in the source code of your destination.

Secondly if your Activity is started from many different places then it will be a pain to update if you ever decide it needs to take different parameters, and you’ll only find out if you missed something at run-time. It would be much better if we could get the compiler to let us know what we’ve broken when we change the contracts between screens.

A solution to this is to include a static method on Activities that returns an intent to start it, this makes the intent extras an implementation detail that the caller activity no longer need to know about. It also makes the different permutations of extras you’re allow to start an activity with clear. Finally, it means that if you do change what extras are required then updating this method will prompt you to fix all it’s usages.

Should make it clearer for consumers of HelpActivity that userId is optional

It’s sort of a factory pattern applied to Android activities and intents and it should speed up your development by preventing run-time bugs. Especially as your activity intents become more complicated and your app contains more activities.

1 — https://developer.android.com/guide/components/intents-filters

--

--