Saturday, March 9, 2013

Shift to Octopress Postponed

For some time now, I have been toying with the idea of migrating this blog to octopress. I'm already using Markdown to compose my posts, so this is a logical step for me. Also, the idea of a static site that I can take with me wherever I choose to host it appeals to me. Finally, there's the geek factor what with git-based publish workflows and SCSS/liquid customizations and what not. I had even chosen a theme - Fabric - to use as my base theme.

However, it looks like I'm going to have to postpone migration to Octopress. Here are some of the reasons:

Redirection

I'm not sure how to deal with links to my existing posts. I have seen examples of how to do this if you are self-hosting your current blog, or if you are using your own domain name. Neither of these apply to me - my current blog is hosted on blogger, with a .blogspot domain.

Comments

I'm already using Disqus for comments on my blog. I gather that it should be possible to migrate Disqus comments even if your domain changes. I just haven't figured out how.

Importing

I tried using some custom Ruby scripts to import my existing posts into Octopress. While it works, there are two problems I need to deal with:

  • Syntax Highlighting: In blogger, syntax highlighting is done dynamically by Javascript (I use google's prettify.js). While this can be used with static site generators, it is best to stick to introducing syntax highlighting at the post generation time. This is all fine for new posts, but for posts that I import from blogger, this needs additional tweaking. Basically the imported sources are just HTML with some YAML front-matter. I will need to convert it to markdown, add the syntax highlighting annotations and then generate the posts from it.

  • Permalinks: This goes back to the redirection I already mentioned. I also need to customize the permalinks of imported posts to make sure they play nice with redirection. Again, this is not a problem for newer posts. Only the imported posts need to be tweaked.

Looking Forward

I'm not saying that any of the above impossible (or even very difficult) to achieve. It is just that some amount of experimentation is involved. I feel that it would take up more time than I am willing to invest at this point to get things up and running.

This is not to say that I have shelved the idea of shifting to a static site generator altogether. On the contrary. This shift is surely happening. It has just been deferred.

The easiest approach would be to maintain my current blog at http://curioustechizen.blogspot.com/ and start the octopress blog afresh. No imports from blogger. No redirection. Only new posts at the new blog. This approach is not without its downsides though.

So, in a nutshell:

I will surely be migrating to a static site generator like octopress in the near future. But for now, I'm sticking with blogger.


Monday, February 18, 2013

Android Constants: Preference Keys, Actions, Extras and more

The content of this post may seem ... well .. trivial at first, but I have tripped over these so many times that I decided to write it up - at least to keep me reminded of it, if not for any other reason!

If you have written anything more than a HelloWorld app in Android, chances are you have had to work with a plethora of program elements that are represented as Strings. Consider this sampling:

  • Keys for SharedPreferences are Strings
  • Keys for Bundles are Strings
  • Intent extras are Bundles, and hence, if you want to include any extras or retrieve them from Intents, you use their String keys to work with them. Ditto with Fragment arguments
  • Intent and IntentFilter actions (and categories) are Strings themselves
  • . . .

I used to deal with these the lazy way: Declare the keys as public static where they are first used (or where they "belong" logically) and refer to them from wherever they are needed in the code. Examples of the class that is the logical owner might be:

  • The class that broadcasts an Intent
  • The class that creates or sends a non-broadcast Intent (this might be an Activity or Service for example)
  • The class that creates a SharedPreference for editing

However, I quickly found out that often it is not possible to cleanly define these keys as belonging to a particular class. Further, since you might end up with a handful of extras, qualifying the class name becomes tedious - more so since it is likely that Activities or Services can have quite long names. How readable is this snippet?

if(AbstractBaseLiveModeActivity.ACTION_LIVE_UPDATE.equals(intent.getAction())){
    Bundle extras = intent.getExtras();
    if(extras.containsKey(AbstractBaseLiveModeActivity.EXTRA_LIVE_UPDATE_TIMESTAMP)){
        long timestamp = extras.getLong(AbstractBaseLiveModeActivity.EXTRA_LIVE_UPDATE_TIMESTAMP);
        // Do something with timestamp here
    }
}

Constants Almighty

One common solution to this problem is to put everything into one "God" object called Constants or whatever, and prefix the constant names with EXTRA_, ACTION_ or other such descriptive characters to keep them distinct.

public class Constants{
    private Constants(){}

    public static final String ACTION_LIVE_UPDATE = "com.myawesomeapp.action.LIVE_UPDATE";
    // ...

    public static final String EXTRA_LIVE_UPDATE_TIMESTAMP = "com.myawesomeapp.extra.LIVE_UPDATE_TIMESTAMP";
    // ...

}

Now, we've solved the readability problem since we just qualify the constant names with Constant. So, all's well, right?

Wrong!

The problem with this approach is as the number of extras, actions and preference keys increases, the Constants class quickly becomes unmanageable. Also, having to use the ACTION_ and EXTRA_ prefixes hinders usability with some IDE's. For example, with Eclipse, even if you know that you want EXTRA_LIVE_UPDATE_TIMESTAMP, you are forced to type the first six characters without which the code assist will not be able to filter only the extras.

Try using Eclipse to find a particular action or extra from the Intent class if you want to see a real-world example of what I mean.

Split it up into distinct constant files

Here's what I do to keep my code free of such stutter. I simply split up the "God" Constants class into several smaller, easier-to-manage constants classes. Like so:

public class Extras{
    private Extras(){}

    private static String createExtra(String suffix){
        return Constants.NAMESPACE_PREFIX + ".extra."+suffix; //NAMESPACE_PREFIX could be "com.myawesomeapp"
    }

    public static final String LIVE_UPDATE_TIMESTAMP = createExtra("LIVE_UPDATE_TIMESTAMP");
    public static final String LIVE_UPDATE_VALUE = createExtra("LIVE_UPDATE_VALUE");
    public static final String FRIEND_ID = createExtra("FRIEND_ID");
    // ...

}

public class Broadcasts{
    private Broadcasts(){}

    private static String createBroadcast(String suffix){
        return Constants.NAMESPACE_PREFIX + ".broadcast."+suffix; //NAMESPACE_PREFIX could be "com.myawesomeapp"
    }

    public static final String LIVE_UPDATE = createBroadcast("LIVE_UPDATE");
    public static final String FRIEND_OFFLINE = createBroadcast("FRIEND_OFFLINE");
    // ...
}

public class Actions{
    private Actions(){}

    private static String createAction(String suffix){
        return Constants.NAMESPACE_PREFIX + ".action."+suffix; //NAMESPACE_PREFIX could be "com.myawesomeapp"
    }

    public static final String JOIN_CHAT = createAction("JOIN_CHAT");
    // ...
}

You could create classes for Categories, Preference Keys and so on. Note that I differentiate between Broadcasts and Actions because although they are both Intents, they are logically very different. Now, this code snippet changes to:

if(Broadcasts.LIVE_UPDATE.equals(intent.getAction())){
    Bundle extras = intent.getExtras();
    if(extras.containsKey(Extras.LIVE_UPDATE_TIMESTAMP)){
        long timestamp = extras.getLong(Extras.LIVE_UPDATE_TIMESTAMP);
        // Do something with timestamp here
    }
}

Which code snippet would your rather see, especially six months from now when you have to fix a bug? Also note that we've made it far more easy to find the exact action or extra that we want using our IDEs.

Wait, what about constants in XMLs?

Glad you asked. In android, many of these constants are used not only in Java code, but also from XML files.

  • Preference keys can be referenced in preferences XML files via the <PreferenceScreen> element.
  • Intents can be declared in AndroidManifest.xml. This means, the Intent action and categories can be referenced from the manifest.
  • BroadcastReceivers can be declared in AndroidManifest.xml. The <intent-filter> action and categories are referenced here.
  • . . .

This presents a problem since we end up duplicating the constants here. We cannot use our Broadcasts.LIVE_UPDATE constant in XML, so we tend to repeat the constant value:

<intent-filter>
    <action android:name="com.myawesomeapp.broadcast.LIVE_UPDATE"/>
</intent-filter>

This is not good. Any change to any constant involves updating it at multiple places. What's more, these issues are not caught at compile time and can be hard to debug.

Using String resources to avoid duplication

One way to avoid constant literal duplication issue explained in the previous section is to use string resources. You are already using string resources for a variety of strings in your Android app. (Wait, you aren't? I strongly suggest you start doing so right now). All you need to do is add the constants as additional string resources.

To keep things clean, you could keep these constants in their own file under values/ folder - for example constants.xml. In there, you could add

<resources>

    <!-- Broadcast Actions -->
    <string name="broadcast_live_update">com.myawesomeapp.broadcast.LIVE_UPDATE</string>
    <string name="broadcast_friend_offline">com.myawesomeapp.broadcast.FRIEND_OFFLINE</string>

    <!-- Intent Extras -->
    <string name="extra_live_update_timestamp">com.myawesomeapp.extra.LIVE_UPDATE_TIMESTAMP</string>
    <string name="extra_live_update_value">com.myawesomeapp.extra.LIVE_UPDATE_VALUE</string>
    <string name="extra_friend_id">com.myawesomeapp.extra.FRIEND_ID</string>

    <!-- Preference Keys -->
    <string name="pref_key_update_interval">UPDATE_INTERVAL</string>
    <string name="pref_key_theme">THEME</string>

</resources>

Then, you could access these values from XML as follows:

<intent-filter>
    <action android:name="@string/broadcast_live_update"/>
</intent-filter>

<Preference 
    android:key="@string/pref_key_update_interval"
    ... />

And so on. In Java code, you'd access these as:

if(getString(R.string.broadcast_live_update).equals(intent.getAction())){
    // ...
}

mSharedPref.getLong(getString(R.string.pref_key_update_interval));

Unfortunately, this solution has all the disadvantages I mentioned in an earlier section.

Your constants.xml will quickly become a monolithic clutter. This can be addressed by creating a separate XML file for each type of constant - like broadcasts.xml, pref_keys.xml etc. Even if you do that, you will still be accessing all the resources using @string/blah and R.string.blah.

Also, IDE content assist is still a problem. Your resource names will need to be prefixed with action_ or broadcast_ or pref_key_ etc and finding the key you need could be frustrating.

A workable strategy

Here's a strategy I follow to decide how I should declare these constants:

  • For preference keys, prefer string resources. This is because you are most likely to be building your Settings screens with XML anyway.
  • For all other key constants, prefer split constant files.
  • Only if you need to use these from XML, declare them as string resources.

Friday, February 1, 2013

Android: Passing an arbitrary object to a custom View

So, I came across a situation where I wanted to create a custom View in Android (let's call it MyAwesomeView). I had to work with a couple of constraints:

  1. I have to be able to pass in an additional object to MyAwesomeView.
  2. The MyAwesomeView should also be usable from XML.
  3. The MyAwesomeView should be distinct from the application itself - i.e., it should be possible to distribute the MyAwesomeView as a library.

To elaborate a bit on the "pass in an additional object" part: View provides three standard constructors using which you can pass in

  • a Context,
  • an AttributeSet and
  • an int representing the style.

I want to also pass in a BitmapCache object since MyAwesomeView uses lots of Bitmaps and I don't want to encounter the dreaded OutOfMemoryError that goes hand in hand with decoding large bitmaps in an Android app. MyAwesomeView decodes a bitmap only if it is not already present in the cache.

The second constraint makes things really difficult. It is possible to pass in additional "configuration" information to a View by creating custom attributes. However, this obviously cannot be used to pass in an object like a BitmapCache.

Augmenting the Context object with additional information

This solution I came across is as follows:

  • Define an interface BitmapCacheProvider with a single method provideBitmapCache();
  • Make your Activity class implement the interface defined in step 1. Override the interface method to return an appropriate BitmapCache object.
  • In the constructor of MyAwesomeView, check to see if the context object passed in to implements the BitmapCacheProvider interface. If it does - we're good. If not, then fail fast (or disable cacheing - whatever works for you).

In code, here's what this would look like:

/**
 * Interface to be implemented by the Context (Activity etc) in which `MyAwesomeView` runs
 */
public interface BitmapCacheProvider{
    BitmapCache provideBitmapCache();
}

/**
 * An example of an Activity that implements BitmapCacheProvider
 */

public class MyActivity extends Activity implements BitmapCacheProvider{
    //... Life-cycle methods of the Activity here

    @Override
    public BitmapCache provideBitmapCache(){
        //Get your instance of bitmapcache here - probably from your Application
        BitmapCache bitmapCache = ...;
        return bitmapCache;
    }
}

/**
 * Custom View that uses an additional object (BitmapCache) for its configuration.
 */
public class MyAwesomeView extends View{
    private BitmapCache mBitmapCache;

    public MyAwesomeView(Context context){
        init(context, null, 0);
    }

    public MyAwesomeView(Context context, AttributeSet attrs){
        init(context, attrs, 0);
    }

    public MyAwesomeView(Context context, AttributeSet attrs, int style){
        init(context, attrs, style);
    }

    private void init(Context context, AttributeSet attrs, int style){
        try{
            /*
             * Try casting the contex to BitmapCacheProvider. 
             * 
             * If the required interface is not implemented, 
             * it'll throw a ClassCastException
             */
            mBitmapCache = ((BitmapCacheProvider) context).provideBitmapCache();
        } catch(ClassCastException e){
             throw new ClassCastException(context.toString()
                    + " must implement BitmapCacheProvider");
        }

        //At this point, we have the BitmapCacheObject which we can use for further processing.
    }

}

Conclusion:

What we saw in this post was how it is possible to create a custom View in Android, that can take in an arbitrary object in its constructor - and still be usable from XML. Admittedly, it is a bit round-about, but it has its benefits. Here are a few other points worth considering if you are following this approach:

  • In this example, I just augmented the main Activity with the desired interface, but you might need to do this for other classes. Basically, the Context that is passed in to the custom View constructor must be enhanced to implement the interface. What this context is depends on how you are including the custom View.
  • You might argue that the BitmapCache should be part of the custom View and not passed in to it by the application. This depends on the use case. If you have multiple custom Views that require Bitmap cacheing (as is the case with my app), it probably makes sense for the app to maintain the cache. We might not want too maintain too many caches lest the cache overhead cancels out any benefits we derive from having the cache in the first place!

Tuesday, January 29, 2013

Android: is onDestroy the new onStop?

Conventional Android development logic dictates that if there is some action you want to perform (or rather, stop performing) when your Activity is no longer visible to the user, do it in onStop(). Likewise, if there is some action you want to restart performing when the user restarts interacting with your Activity, do it in onStart(). The disadvantage of this approach, of course, is that it wouldn't play well with device orientation changes.

This post explores a couple of solutions to this problem, and concludes that there are cases where one has no choice but to postpone the actions that would be ideally taken in onStop(), to onDestroy().

A trivial (incorrect) example

public TrivialIncorrectActivity extends Activity{

    //onCreate() and other life-cycle overrides like onResume() go here ...

    @Override public void onStart(){
        super.onStart();
        startMakingThatPeriodicRestCall();
    }

    @Override public void onStop(){
        super.onStop();
        stopMakingThatPeriodicRestCall();
    }

    // ... Other life-cycle overrides like onDestroy() go here

}

This example is incorrect. Every time the user rotates the device, your app would stop making a REST call and then again start making the call. Not good at all.

setRetainInstance to the rescue . . .

API 11 introduced the Fragment API, and along with it, the setRetainInstance method, which is also usable with older versions of Android by means of the support library. You can go through the documentation to understand the effect of a setRetainInstance(true). Essentially, when a configuration change is happening, even though the hosting Activity is being re-created, the Fragment instance is not destroyed.

So, this allows us to improve upon our previous example.

public IncorrectRotationTolerantActivity extends FragmentActivity{

    private static final String TAG_RETAIN_FRAGMENT = "RetainFragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                .add(IncorrectRetainFragment.newInstance(), TAG_RETAIN_FRAGMENT).commit();
        }
    }
}

public class IncorrectRetainFragment extends Fragment{

    public IncorrectRetainFragment(){}

    public static IncorrectRetainFragment newInstance(){
        IncorrectRetainFragment frag = new IncorrectRetainFragment();
        frag.setRetainInstance(true);
        return frag;
    }

    @Override
    public void onStart() {
        super.onStart();
        startMakingThatPeriodicRestCall();
    }

    @Override
    public void onStop() {
        super.onStop();
        stopMakingThatPeriodicRestCall();
    }

}

This code snippet still doesn't do what we want it to do. It does not prevent re-making that REST call during orientation changes. Why?

Because, setRetainInstance doesn't prevent a Fragment's onStop() from being called - it just prevents onDestroy() from being called. So, even if you ask for a Fragment instance to be retained across configuration changes, the onStop() method of the Fragment is always still called when the device is rotated.

onDestroy() is the new onStop()

To fix the problem, postpone stopping the REST call to the onDestroy() of the Fragment. Similarly, start making the call in onCreate() instead of in onStart(), since onCreate() is not called when the device is rotated, but onStart() is.

public RotationTolerantActivity extends FragmentActivity{

    private static final String TAG_RETAIN_FRAGMENT = "RetainFragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                .add(RetainFragment.newInstance(), TAG_RETAIN_FRAGMENT).commit();
        }
    }
}

public class RetainFragment extends Fragment{

    public RetainFragment(){}

    public static RetainFragment newInstance(){
        RetainFragment frag = new RetainFragment();
        frag.setRetainInstance(true);
        return frag;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onStart(savedInstanceState);
        startMakingThatPeriodicRestCall();
    }

    @Override
    public void onDestroy() {
        super.onStop();
        stopMakingThatPeriodicRestCall();
    }

}

This seems so semantically wrong though. onDestroy() represents the end of the entire lifetime of an Activity/Fragment and what we really wanted to do was monitor the visible lifetime. Also, there is no guarantee that onDestroy() will ever be called. If you really try out this example on a phone or emulator, chances are that you'll never see the Rest call being stopped - at least not right away.

A more correct, more restrictive solution:

There exists another solution to this problem - but it works only on API 11 and later, because it uses methods introduced in API 11 - isChangingConfigurations() and getChangingConfigurations().

public RotationTolerantActivity extends FragmentActivity{

    private boolean mRotated;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Boolean nonConfigState =
            (Boolean)getLastCustomNonConfigurationInstance();
        if (nonConfigState == null) {
            mRotated = false;
        } else {
            mRotated = nonConfigState.booleanValue();
        }
    }

    @Override 
    public void onStart(){
        super.onStart();
        if(!mRotated){
            startMakingThatPeriodicRestCall();
        }
    }

    @Override
    public void onStop(){
        super.onStop();
        mRotated = false;
        if (isChangingConfigurations()) {
            int changingConfig = getChangingConfigurations();
            if ((changingConfig & ActivityInfo.CONFIG_ORIENTATION) == ActivityInfo.CONFIG_ORIENTATION) {
                mRotated = true;
            }
        }

        if(!mRotated){
               stopMakingThatPeriodicRestCall();
        }
    }

    @Override
    public Object onRetainCustomNonConfigurationInstance() {
            return mRotated ? Boolean.TRUE : Boolean.FALSE;
        }

}

This solution is semantically correct, and works as expected. However, it only works on API 11 and higher, even though we extend FragmentActivity from the support library .

Bonus: Why onStop() and not onPause()?

The keen reader would have observed that this post talks about stopping un-needed tasks in onStop()and not onPause() - even though onPause() is the only one of these methods that is guaranteed to be called. Remember that after onPause() is called, the process could be killed in order to reclaim memory and thus onStop() and onDestroy() might never be called.

Yet, this entire post insists on using onStop() to stop un-needed tasks. The reason for this lies in the technique used in my library android-app-pause. Unfortunately, this library in its current form does not handle device orientation changes correctly. This will be fixed in a future release though.

Saturday, January 5, 2013

Extensibility and Immutability in Java

Objective:

To devise a way to make thread-safe, a Java class designed to be extensible.

Introduction:

Effective Java, Second Edition: Item 15 says "Minimize Mutability". One should always try to make a class immutable. This has several advantages that I will not go over here (Since Effective Java explains it all). I will however point out one of those advantages since it is central to this discussion:

Making a class immutable is the easiest way to ensure that the class is thread-safe.

There is however a problem: to make a class truly immutable, you must prevent it from being sub-classed. Either the class must be declared final, or it should have a private constructor and provide static factory methods instead of constructors. The reasons for this are outlined in Effective Java. The basic premise is that a sub-class can violate the immutability guarantees.

This must-not-be-subclassed restriction may be fine if you are applying immutability to some value object like User, Point, Account etc. However, the same requirement turns out to be overly restrictive if you are applying the concept to logic classes. This is because logic classes are often meant to be customized by extension.

A strongly-immutable logic class:

As an example of a logic class, consider the following ReportGenerator:

public final class ReportGenerator{
    private final DatabaseLayer mDatabaseLayer;
    private final PresentationLayer mPresentationLayer;

    public ReportGenerator(DatabaseLayer db, PresentationLayer pres){
        this.mDatabaseLayer = db;
        this.mPresentationLayer = pres;
    }

    public void generateMonthlyReport(User user){
        Report report = mDatabaseLayer.getReport(user);
        mPresentationLayer.present(report);
    }
}

The other classes have been ommitted for brevity. Assume that DatabaseLayer and PresentationLayer classes are themselves immutable. This makes ReportGenerator strongly immutable and hence, thread-safe.

Now, suppose in the next phase of the project, you need to add a way to generate a historical report. The easiest way that comes to mind is to inherit from ReportGenerator. Unfortunately, we cannot do this since in order to make ReportGenerator immutable, we have declared it final. One possible approach to solving this issue is making ReportGenerator weakly immutable. This is discussed in the next section.

A weakly-immutable logic class:

One can relax the restriction that an immutable class must not be extensible, while still maintaining the guarantees, provided the sub-class adheres to the established contract. This is done by removing the final modifier from the class declaration, and making all fields protected final, or keep them private final and provide getters which we then use in the sub-classes. Both these approaches are shown in the code below.

public class ReportGenerator{
    protected final DatabaseLayer mDatabaseLayer; //protected field approach
    private final PresentationLayer mPresentationLayer; //private field with accessor approach

    public ReportGenerator(DatabaseLayer db, PresentationLayer pres){
        this.mDatabaseLayer = db;
        this.mPresentationLayer = pres;
    }

    public PresentationLayer getPresentationLayer(){
        return this.mPresentationLayer;
    }

    public void generateMonthlyReport(User user){
        Report report = mDatabaseLayer.getReport(user);
        mPresentationLayer.present(report);
    }
}

We can now sub-class this as follows:

public class HistoricalReportGenerator extends ReportGenerator{

    public HistoricalReportGenerator(DatabaseLayer db, PresentationLayer pres){
        super(db, pres);
    }

    public void generateHistoricalReport(User user, Duration duration){
        Report historicalReport = mDatabaseLayer.getReport(user, duration);
        getPresentationLayer().present(historicalReport);
    }
}

We could also have added more protected final fields to the sub-class if needed.

What we now have is a weakly immutable class. This class is immutable as long as sub-classes adhere to the contract. It is a good idea to establish in the class javadoc, the expectation that sub-classes MUST preserve the same weak immutability restrictions that this class adheres to. If a sub-class willfully violates the contract, then the logic class cannot be depended upon to work correctly.

Here's an example to how to establish this contract:

/**
 * The logic class that generates the report.
 * ... ...
 * <br/><br/>
 * This class is <em>weakly immutable</em>. It has been kept open for 
 * extensibility. Sub-classes <strong>MUST</strong> preserve the immutability 
 * guarantees of this class. In particular, they must have only immutable 
 * fields; and must not override any of the methods defined in this class to
 * return a mutable reference.
 *
 */

public class ReportGenerator{
    //Class body omitted.
}

Since immutability is enforced by documentation rather than by the compiler, this is an acceptable compromise. It allows us to easily create thread-safe classes that are also extensible. This makes writing API's and frameworks that much easier.

Thread-safety is more than Immutability:

Of course, making a class immutable is not the only way to make a class thread-safe. A mutable class can be written such that it is thread-safe too. It is often desirable for an object to change its state during the execution of a program. How that is done is beyond the scope of this article. I suggest looking at Java Concurrency In Practice for details on this topic.

Extending the logic class by Composition:

There exists an alternative way to extend the functionality of ReportGenerator that does not involve inheriting from it: "Favor Composition over Inheritance" (Effective Java, Second Edition, Item 16). For completeness, I present the code for this approach here. Do note that this example uses the strongly immutable form of ReportGenerator.

public final class ReportGenerator{
    private final DatabaseLayer mDatabaseLayer;
    private final PresentationLayer mPresentationLayer;

    public ReportGenerator(DatabaseLayer db, PresentationLayer pres){
        this.mDatabaseLayer = db;
        this.mPresentationLayer = pres;
    }

    public PresentationLayer getPresentationLayer(){
        return this.mPresentationLayer;
    }

    public DatabaseLayer getDatabaseLayer(){
        return this.mDatabaseLayer;
    }

    public void generateMonthlyReport(User user){
        Report report = mDatabaseLayer.getReport(user);
        mPresentationLayer.present(report);
    }
}

public final class HistoricalReportGenerator{
    private final ReportGenerator mReportGenerator;

    public HistoricalReportGenerator(ReportGenerator reportgen){
        this.mReportGenerator = reportgen;
    }

    public ReportGenerator getReportGenerator(){
        return this.mReportGenerator;
    }

    public void generateHistoricalReport(User user, Duration duration){
        Report historicalReport = mReportGenerator.getDatabaseLayer().getReport(user, duration);
        mReportGenerator.getPresentationLayer().present(report);
    }
}

This approach works fine when the class hierarchy is only a couple of levels deep. If it gets deeper than that, then getting a handle to the members of the base class becomes unwieldy. For example, suppose we have the following:

public class AnnualReportGenerator extends HistoricalReportGenerator
public class LeapYearReportGenerator extends AnnualReportGenerator

Now imagine a method in LeapYearReportGenerator needs access to the DatabaseLayer object. The code for this would look lik:

mAnnualReportGenerator().getHistoricalReportGenerator().getReportGenerator().getDatabaseLayer();

This is clearly something you want to avoid. With the composition approach, you also lose the runtime polymorphism advantage.

Conclusion

To summarize what this article discussed:

  • The easiest way to make a class thread-safe is to make it immutable.
  • Strong immutability closes the door on extensibility.
  • It is often convenient to make a class weakly immutable. This allows it to be sub-classed.
  • If you make an immutable class extensible, clearly establish in the javadoc, the contract that sub-classes must preserve the immutability guarantees.

Other than these observations, we also saw that:

  • Immutability is not the only way to achieve thread-safety, and in fact immutability is not always desirable.
  • Instead of inheriting from a weakly immutable class, one can also extend the functionality by composing a class with a strongly immutable object as its member. This has its own pros and cons - and both approaches must be evaluated before deciding on one.

Tuesday, December 18, 2012

Code Smells: Calling Life-Cycle Methods of Program Components Explicitly

Here is some code I see that sets off alarm bells clanging in my head:

Explicitly calling life-cycle methods of components that are outside your control.

Since that sounds oh-so-generic, let me illustrate by way of example.

Assume you are writing a Servlet and your implementation doesn't care whether the request was a POST or a GET (in the current RESTful world, this should never be the case, but let's keep that aside for the purposes of this post). So, the following would appear to be a reasonable implementation:

public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        //Handle the request 
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        doGet(req, resp); //Just call doGet
    }
}

I would never do this though. This is because doGet, doPost and the other doXXX methods are life-cycle methods of the Servlet. I have no control over when and how the servlet engine calls them. I also have no control over what the engine does once these methods return. It is possible that the engine performs some house-keeping tasks once a doGet returns, and that action could be different from what is done once a doPost returns.

It is really a simple matter of extracting the "common functionality" between such life cycle methods into a method and calling that method.

public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        handleRequest(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        handleRequest(req, resp);
    }

    /**
     * Method that extracts out the common functionality between GET and POST requests
     */
    private void handleRequest(HttpServletRequest req, HttpServletResponse resp){
        //Handle the request
    }
}

What if the life cycle methods are in an Interface?

One opinion that came up in a discussion was that it is safe to call other life-cycle methods if they are in an interface as opposed to a class. Note that the above code sample extends javax.servlet.http.HttpServlet which is an abstract class as opposed to the base javax.servlet.Servlet which is an interface. This has come up specially while discussing callbacks.

I disagree with this opinion since it assumes that any book-keeping has to be performed by the same (possibly abstract) class that denotes the life-cycle component. This is not true. Take an imaginary UI toolkit for example, which has a Pane as a UI element. Now, assume an interface for handling interaction callbacks:

interface InteractionListener{
    public void onClick();
    public void onRightClick();
    public void onLongClick();
    public void onDoubleClick();
}

In this case again, assume that you want the same action to be performed on long-click and right-click. So, you might be tempted to do this:

Pane pane = // ...

pane.setInteractionListener(new InteractionListener(){
        public void onClick(){
            //Handle single-click
        }

        public void onRightClick(){
            //Handle right-click
        }

        public void onLongClick(){
            onRightClick();
        }

        public void onDoubleClick(){
            //Handle double-click
        }
});

This is still wrong. Yes- InteractionListener is an interface and there is no way it can have a concrete method that might perform house-keeping tasks. However, you have no control over how the UI toolkit engine invokes the call-backs. You also have no control over what action the engine takes after your onXXXClick() methods return. The solution, again is exactly the same as before: extract the common code into a method which you then invoke from both onLongClick() and onRightClick().

Conclusion

Avoid calling one component life-cycle method from another, when the component in question is outside your control. This could lead to unpredictable behavior. Simply refactor the common behavior into a method and call that method from both life-cycle call-backs.

A few other instances where I have seen this sort of code:

  • Android's SqliteOpenHelper. In the onUpgrade() method, you probably want to take a backup of data, drop the tables, add new columns, and then re-create the tables. The implementation often looks like this:

    public class MySqliteOpenHelper extends SqliteOpenHelper{
        public void onCreate(SQLiteDatabase db){
            //Use SQL CREATE TABLE statements to create the tables.
        }
    
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            /*
             * 1. Take backup of data
             * 2. Drop tables
             * 3. Add columns
             *
             * And finally:
             */
            onCreate(db); //This is not right.
        }
    }
    

    The right way to do this would be:

    public class CorrectSqliteOpenHelper extends SqliteOpenHelper{
        public void onCreate(SQLiteDatabase db){
            createDatabase(db);
        }
    
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            /*
             * 1. Take backup of data
             * 2. Drop tables
             * 3. Add columns
             *
             * And finally:
             */
            createDatabase(db);
        }
    
        private void createDatabase(SQLiteDatabase db){
             //Use SQL CREATE TABLE statements to create the tables.
        }
    }
    

I will re-visit this post and add more instances as and when I come across them.

Monday, December 3, 2012

Android: "Application level" Pause and Resume

Update

I have created an open source library using the concepts presented in this post. You can directly use the library to create your apps. Get it at android-app-pause on github

Introduction

I have often come across questions on StackOverflow and the android-developers google group about an Application-level onPause() and onResume(). In this post, I present one of the ways of achieving such functionality. But before that, what exactly do I mean by an app-level onPause()?

After all, an Android app consists of multiple components, several of which might be in the background. There could be Services, Threads, BroadcastReceivers, scheduled Alarms. How do these figure in a "paused" app? Well, here's my definition of an app being paused for the purposes of this post:

An app is considered to be paused when the app is no longer visible to the user. By definition, this means that when an app is paused, none of the Activities that belong to the app are visible to the user.

In my opinion, this is a fair definition since this would typically be the point when the app wishes to "pause" any background work it does. For example, an app might wish to cancel all scheduled alarms, or stop making HTTP calls when it knows that the user is no longer interacting with the app.

Similarly, an app is considered to be resumed when at least one Activity from the app is visible to the user.

This is the point at which the app can re-establish HTTP communication, re-schedule alarms and the like.

TL;DR

I got this idea from this answer that I gave on stackoverflow. The basis of this approach is that when an Activity starts another, both of them undergo lifecycle changes in a predictable fashion. The series of steps to follow to achieve the app-level pause and resume functionality is as follows:

  1. Create a bound Service (let's call this AppActiveService).
  2. In the onStart() of every Activity of your app, bind to AppActiveService.
  3. In the onStop() of every Activity of your app, unbind from AppActiveService.
  4. The onDestroy() method of AppActiveService represents the point when your app is "pausing"; while the onBind() method represents the point when your app is "resuming". Put the code you want to be run when your app "goes to the background" in AppActiveService's onDestroy() method.

To make things even simpler, you can put all the code above in a BaseActivity for your application and have all your other Activities inherit from this BaseActivity.

If you follow the steps above, the AppActiveService will have at least one Activity bound to it as long as your app is visible to the user. When this condition is false, no Activity is bound to the Service, at which point its onDestroy() is called.

Do note that we are using onStop() and not onPause() to un-bind from the Service. If you were to use onPause(), then there would be zero components bound to AppActiveService even as you are switching from one Activity to the other within your own app.

Gotchas

One gotcha in this approach is: What happens if your app "starts another app" using an Intent? No Activity from your app will be visible to the user - thus triggering an app-pause. Whether this is acceptable or not depends on your use case.

Conclusion

I plan to publish the code for this procedure as a library or at least as a gist on GitHub. Before that, I'm looking for feedback on how the code can be improved and made more robust. Have you come across the need to know when your app as a whole is "going away"? How have you solved the problem?