Refactoring Simplenote2

Simplenote is an Open Source note taking application published by Automattic. Source for the Android client is available on github.

AboutFragment.java

Here’s the original source file on github.

The things that stand out to me

  1. The method onCreateView() is really long; obscuring that it mostly initializes some click handlers.
  2. A big block of View and TextView assignments
  3. A long list of OnClickListener attached to the views but disconnected from the View declaration.
  4. Some click listeners with the same click responses.

View reconciliation

The first thing to do is to get the view assignments closer associated with the click listener assignments. That should make it easier to extract methods from onCreateView() later.

I mostly write in Kotlin these days, so there may be a better way to do this in Java. For now though, I have created a static method to get the view assignment and the click handler closer together.

Now, the about_blog click handler looks like this:

Some of that common click handler behavior can be gathered into a private function.

There’s a bit of YAGNI with that default version with the parameterized URL but I’m ok with that for now. Next, use the same approach for the TextView click handlers.

This change gets the view assignment and click handler closer together. But it doesn’t really get very far in the overall goal of shortening the onCreateView() function.

Here’s the shortened onCreateView() after extracting and grouping functions.

To me, reading this function out seems like an improved explanation of what the function is doing.

View click handling gets setup here.

Here’s the final, refactored result.

Summary and takeaways

These refactors only reduce the file’s LOC by 10 lines. Even though there isn’t a lot of functionality in this fragment, I think it was worth the effort to make it more readable. It makes it a lot less likely that the next developer will jam some unrelated code into the function named handleViewClicks(). I couldn’t confidently say that about the original onCreateView() method.