Mickey Williamson

Program to an Interface

If you’re in the Object Oriented Programming world any length of time, you’re going to hear the design principle, “Program to an interface, not an implementation.” But what exactly does that mean?

First, it can be a bit misleading because the word interface is not used in the sense of the OOP programming structure used to provide additional behavior and functionality to classes. It means program to the supertype, not to subtypes. Let’s take a look at a concrete example.

Let’s create a Storm class which we’ll then extend to the subtypes of SnowStorm and RainStorm. Below is the UML diagram. We have the Storm class with a precipitate() method and then two classes that inherit from Storm.

The Storm, RainStorm, and SnowStorm classes in code:

public class Storm {
    public void precipitate() {}

public class RainStorm extends Storm {
    public void precipitate() {
    public void rain() {}

public class SnowStorm extends Storm {
    public void precipitate() {
    public void snow() {}

We might be tempted to do the following when creating RainStorm and SnowStorm objects which is an example of “programming to an implementation”:

RainStorm rainStorm = new RainStorm();
SnowStorm snowStorm = new SnowStorm();

A better way would be to “program to an interface (supertype)” by setting the declared type of the variable (rainStorm and snowStorm below) to the supertype (Storm) and setting the object assigned to the variable as an implementation of the supertype (RainStorm or SnowStorm). More succinctly, that is, supertype on the left and subtype on the right of the equals sign.

Storm rainStorm = new RainStorm();
Storm snowStorm = new SnowStorm();

By doing it this way, we don’t need to know what type of storm it is at runtime. So if we added a static factory method that returns a subtype, we could still make that storm send down its appropriate precipitation without needing to know what type of storm it actually is while we’re coding it. See the MotherNature class at the end of the snippet below.

public class Storm {
    public void precipitate() {}
    public static Storm generateStorm(String type) {
	Storm storm; 
	switch (type) {
	    case "rain":
		storm = new RainStorm();
	    case "snow":
		storm = new SnowStorm();
		storm = new Storm();
        return storm;

public class RainStorm extends Storm {
    public void precipitate() {
    private void rain() {} // By programming to an interface, this can be changed to private

public class SnowStorm extends Storm {
    public void precipitate() {
    private void snow() {} // By programming to an interface, this can be changed to private

public class MotherNature {
   public static void main(String[] args) {
        // We don't even need to know the type of storm.
        // The type can be determined at runtime by what the user passes in.
	Storm storm = Storm.generateStorm(args[0]); 

Hopefully this has demystified what it means to “Program to an interface, not an implementation”.

Android Fragments and Static Factory Methods

Typically when we create a class, we create one or more constructors for the class:

public MyClass {

    private int myInt;
    private String myString;

    public MyClass(int someInt) {}

    public MyClass(int someInt) {
        myInt = someInt;

    public MyClass(String someStr, int someInt) {
        myInt = someInt;
        myString = myString;

We then use the “new” operator to instantiate the class and pass in an argument:

MyClass myClass = new MyClass(5);
MyClass myClass = new MyClass("Take", 5);

This works in the more common scenarios but isn’t flexible enough in others. What if we needed to:

  • Return an subclass of the class instead of the class itself
  • Return a subclass of the class based on the parameters passed in
  • Return an already created instance of the class instead of a new instance (cache, singleton)
  • Have multiple constructors with the same signatures?

Enter Static Factory Methods.

[Note: Static Factory Methods are not connected with the Factory Method design pattern.]

Instead of using constructors to instantiate objects, we use public methods with names that describe what they do. Example method names include from, of, valueOf, instance, getInstance, create, and newInstance.

For instance, the valueOf method of the String class is one such static factory method. Instead of creating a string using the string’s constructor String myString = new String(5), valueOf is an overloaded method that takes several different kinds of parameters, converts them to a string and returns a string object:

String myString = String.valueOf(2);

Uses of Static Factory Methods in Android

Examples of the use of static factory methods in Android include:


Instead of using a constructor, the LayoutInflater is obtained from context using the from method:

LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.some_layout, root);)


The NotificationManagerCompat class is also instantiated from context using the from method:

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(0, notificationBuilder.build());


When extending the Fragment class, if data is to be passed into the Fragment, it is best practice to create a static newInstance method that receives the data and passes the data in a Bundle using setArguments so it can be retrieved from the Bundle with getArguments. This is because when the device is rotated or other configuration change is made, the fragment is destroyed and recreated. When the system recreates the fragment the default empty constructor is used (which is why the compiler complains if there is no empty constructor on a Fragment subclass). So if you create a second constructor that get arguments passed in, that constructor will never be called and the data will never get passed in. By passing and retrieving the data via the Bundle, it doesn’t get destroyed along with the fragment and is available to the fragment when it is recreated by the system.

public class MyFragment extends Fragment {

    public static MyFragment newInstance(int myInt) {
        MyFragment myFragment = new MyFragment();

        Bundle args = new Bundle();
        args.putInt("myInt", myInt);

        return myFragment;

    public void onCreate(@Nullable Bundle savedInstanceState) {
        getArguments().getInt("myInt", 5);
MyFragment fragment = MyFragment.newInstance(5);


Hopefully that demystifies the use of the newInstance method for extending the Fragment class when passing in data. It is simply a static factory method used to instantiate a class rather than using a constructor.

For additional enlightening information on static factory methods, see Effective Java (Third Edition) by Joshua Block – Item 1.

Database inspection window in Chrome DevTools from Android emulator

Set Up Stetho to View Your Room Database

Building an app that uses a backend database for persistent data storage without access to the database can be like playing darts in the dark. While building out the app’s functionality, how do you know whether data is getting stored in the database correctly or even at all? There are several methods for viewing your Room database from an Android device or emulator. In this blog post, I’m going to talk about how to set up Facebook’s Stetho to view your database.

  1. Add the Stetho dependency to your app’s build.gradle file:
    implementation 'com.facebook.stetho:stetho:1.5.1'

  2. Extend the Application class in your app and initialize Stetho:
    public class MyApplication extends Application {
    public void onCreate() {

  3. Make sure your MyApplication class is referenced in the main application tag in your manifest.xml:

  4. Run your app from Android Studio

  5. Visit chrome://inspect/#devices in your Chrome browser. Your app will be listed. Click the inspect link under its name and a new DevTools window will be launched.

  6. To view the database, expand “Web SQL” in the menu on the left and you’ll see your database listed. Click to expand to view the tables.

No need to throw darts in the dark and wonder where they landed anymore!

11 Ways I Keep Up With Technology

The field of technology changes at a rapid pace. I know people for whom the rate of change would be their worst nightmare. My worst nightmare would be working on an assembly line doing the same thing day after day, bored out of my skull, and not regularly learning something new. I thrive on the change. Learning and expanding nourishes my soul!

However, the field of technology is so vast and deep that unless one specializes in a small niche area, it’s difficult to keep up. There are many trails I’d love to follow – cybersecurity, systems programming, and embedded programming to name a few – but there just aren’t enough hours in a day. Just trying to keep up with frontend web development is a challenge, not to mention the various versions of Drupal and Magento. And then there’s the world of Android that I’ve fallen in love with. Just staying on top of it all feels impossible, much less getting to the leading edge.

But that’s what I love. There is less than zero possibility that I will get bored as there is ALWAYS something new to learn. And the steeper the learning curve, the better.

So how do I even attempt to stay on top of my chosen areas of tech? Here’s a little rundown:

  1. First and foremost, I ditched the TV. I haven’t owned a TV in over 25 years. While most people are consuming 2 or 3 or more hours of TV per day, I’m reading books and articles, watching videos, working on side projects, etc. That’s not to say I don’t enjoy a good Netflix binge every now and again when my brain is just fried and I want to be entertained and not have to think. But that’s the exception, not the rule.
  2. I read. A lot. I’m generally reading 3 to 5 books at any given time. At least one or two of those is usually a tech book. I average about a book per week with one book per month being a tech book. I have a list a mile long of tech books I want to read and regularly reprioritize them according to whatever I’m planning to work on next. If I’m currently working on a Drupal project and I know I’m going to be starting a Magento project next month, I’ll be working my way through a couple of the latest Magento books. If I don’t have any projects on the horizon for which I need to update my knowledge, I get to dig into a book that expands my general programming skills, like I’m doing this summer.
  3. I make it a priority. My morning routine includes a good hour of reading whatever tech book I’m into. It’s not a chore. It’s what gets me out of bed in the morning. I have to discipline myself to close the book and get on with the rest of life. I do it in the morning so that it doesn’t get pushed aside for the “responsibilities” of life.
  4. I keep a list of topics that I want to learn or go deeper into and then collect resources for learning those topics. I am forever looking for the holy grail for learning a particular subject and when I find a new resource that looks promising, I add it to the list. Then when I’m ready to tackle that subject (like Kotlin, for instance), I compare the various resources I’ve accumulated and pick the one that looks the best.
  5. I maintain a Safari Books subscription and consider it the best thing since sliced bread. It gives me access to almost every book available from the major and minor tech publishers along with loads of videos. If I want to read a chapter on a certain topic, I can read it through Safari and don’t need to buy the entire book.
  6. I use YouTube extensively to watch videos from conferences I couldn’t make it to and subscribe to various channels on programming and Android development.
  7. I use the Android Play Music app to subscribe to podcasts and listen to them while I’m driving/running/mowing the grass/etc.
  8. I keep social media to a minimum. I use Twitter to follow the folks on the bleeding edge and Facebook to keep up with my family and friends. And when I’m caught up with the most recent posts, I close the app, and don’t mindlessly scroll…usually.
  9. It’s all about focus. When I’m involved in something, I’m all in. If I’m reading, my full attention is on reading and digesting what I’ve read. If I’m talking with someone, I’m not checking my cell phone. Whatever I’m doing, I’m giving it my full focus. I’ve found that this saves time in the long run as I make fewer mistakes that need to be corrected and I retain information more fully.
  10. I balance it out with my other interests. While I am very passionate about web and mobile development and computer programming in general, I do have other interests too. And I find that I need a balanced mix of both mental and physical activity. So mixing things up between working on the computer and my physical activities – running, hiking, gardening, raising rabbits, making healthy foods, and spending time with my family – prevents burnout. And leading a rather different (minimalist) lifestyle without all the time-consuming cruft of the average American lifestyle allows me to fit everything into my life.
  11. And finally, it’s an innate desire, an insatiable hunger, as I see so much value and benefits of technology (also the dangers but that’s another post). So it’s not a matter of forcing myself to do anything or trying to use external motivation. It’s what I love doing and I’m excited whenever I get to do it.

So there you have it – my personal recipe for keeping up with technology. It’s not for everyone, but it works for me.

Building blueprints

The Builder Design Pattern

Instantiating Objects with Many Properties

Let’s build a house!  First, let’s decide what kind of house we want to build:

  • Construction type = timber frame
  • Stories = 2
  • Roof type = slate
  • Siding = batten-board
  • Basement = true
  • Attic = true
  • Size = 2000 sq ft
  • Bedrooms = 3
  • Bathrooms = 2
  • Technology = alarm system, motion detected lights
  • Heating = oil, wood, solar
  • Water = well
  • Sewer = septic
  • Trim = stained
  • Windows = double hung

Now let’s create a POJO class to represent our house:

public class House {

    private String constructionType;
    private String roofType;
    private String siding;
    private String water;
    private String sewer;
    private String trim;
    private String windows;
    private String[] technology;
    private String[] heating;
    private boolean basement;
    private boolean attic;
    private int size;
    private int bedrooms;
    private int bathrooms;
    private int stories;

    // Empty constructor
    public House() {}

    // Constructor that includes all settings
    public House(String constructionType, String roofType, String siding, String water, String sewer, String trim, String windows, String[] technology, String[] heating, boolean basement, boolean attic, int size, int bedrooms, int bathrooms, int stories) {
        this.constructionType = constructionType;
        this.roofType = roofType;
        this.siding = siding;
        this.water = water;
        this.sewer = sewer;
        this.trim = trim;
        this.windows = windows;
        this.technology = technology;
        this.heating = heating;
        this.basement = basement;
        this.attic = attic;
        this.size = size;
        this.bedrooms = bedrooms;
        this.bathrooms = bathrooms;
        this.stories = stories;

    public String getConstructionType() {
        return constructionType;

    public void setConstructionType(String constructionType) {
        this.constructionType = constructionType;

    public String getRoofType() {
        return roofType;

    public void setRoofType(String roofType) {
        this.roofType = roofType;

    //...remaining setters and getters


That’s quite a few parameters that can be set and that’s quite the constructor for setting them all! Configuring and creating our new house would look like this if we had constants set for the various options!

House ourHouse = new House(
    new String[] {ALARM_SYSTEM, MOTION_LIGHTS}, 
    new String[] {OIL, WOOD, SOLAR}, 

Now what if our customer is just starting to explore what they want their new house to look like and the only thing they’re currently set on is stick construction, wood heat, a basement, and 2 bathrooms?  The constructor would look like this!

House ourHouse = new House(
    new String[] {}, 
    new String[] {WOOD}, 

We’ve already encountered two problems:

  1. Our constructor is unwieldy.  No programmer is going to remember all the possible parameters or their order.
  2. There are many string parameters in a row and it would be easy to instantiate a house with a property in the wrong position and the compiler would never complain.

An alternative to using this unwieldy constructor would be to use the empty constructor and then the setter for each property:

House ourHouse = new House();
ourHouse.setHeating(new String[] {WOOD});

The problem with this is our house is left in a partially modified state in between setter calls.  

There is a better way.  

Enter the Builder Pattern

Take a look at the following classes in the Android SDK and third party library:

What do all of these seemingly unrelated classes have in common?  They all have lots of possible configurations to the class and they all have a nested class named Builder.  This Builder class solves the problem experienced in the House class example above. Let’s take a look at the Builder class for AlertDialog. Notice all the public methods – most of them are basically just “setter” methods. While the AlertDialog class itself contains some of these setter methods for one-off setting of a property and there is some overlap, the Builder class is much more robust for setting the properties of an AlertDialog.  Notice that the “setter” methods in the Builder class return an AlertDialog.Builder object. This allows us to chain the methods together to build the AlertDialog.

Builder builder = new Builder(this)
    .setNegativeButton(R.string.no, listenerNo)
    .setPositiveButton(R.string.ok, listenerOk);
AlertDialog alert = builder.create();

This way, the required parameters are passed into the Builder object’s constructor and the optional parameters use the “setter” methods on the Builder and the object is created all at once without risking incomplete states as it’s being built.

Now back to building our house…

If a Builder class were available for our house, we might create our house like this:

Builder builder = new Builder()
    .setHeating(new String[] {WOOD})
House ourHouse = builder.create();

That’s much more readable, maintainable, and reliable! Long live the Builder pattern!

Books: Head First Design Patters, Refactoring, Effective Java

A Dream Summer

I am beyond excited for this summer.  In fact, I’m probably as excited as I was the summer I got to hike the 500-mile Colorado Trail across the Rockies with my dog!  Why am I excited?

Self-Directed Learning

I’ve fulfilled the requirements for my Master’s in Computer Science and graduated six months ago. I learned a lot and am glad I did it.  But after two years of it, I was finding the classes restrictive and limiting. I wanted the freedom to dive deeper and explore more broadly but college classes don’t allow for that type of learning.

After graduating, I spent most of my free time of the last six months studying a couple topics unrelated to technology that I’ve been craving to learn more about – regenerative farming and spirituality.   I’m feeling pretty satiated in those areas at the moment and am ready to turn my attention back to technology and dive into the topics I’ve been hungering after for years but never had the chance to pursue.  Now is the time and I couldn’t be more excited! Here is the summer plan…

Books, Certification, Project(s), Prep, and Blogging

There are three classic programming books that I’ve had high on my radar for years.  I feel like they’re the key to getting my programming to the next level. They are:

Effective Java
GoF Design Patterns (in conjunction with Head First Design Patterns)

The plan is one book per month.  That seems like a long time to spend on a book (at least for me – I usually read about one book per week).  But I intend to do more than just read. I intend to take notes and digest as much as possible. I say “as much as possible” because I expect these three books to require several readings over the course of my career to fully assimilate their contents. I expect (and hope!) there will be parts that are a bit beyond what I need at the moment so I plan to absorb as much as I can this first time through them.

In addition to immersing myself in these books, I also plan to go for my Google Android Developer certification.  I have a few topics I want to spend a couple weeks brushing up on in early July and then take the test July 11 so that I’ll hopefully have a shiny new certification to pin to my resume in the fall.

Next on the summer agenda is a project (or two depending on how the first project goes).  A client is in need of a marketplace eCommerce site. So I’ll be building that using Magento as the base.

And lastly, while I do enjoy the web developer freelancing life, I’d really like to get into a top-notch Android agency to polish my Android chops and really gain some expertise in the area. So I’ll be prepping for that – updating my resume and LinkedIn profile, following job openings, putting together a CV site, etc.

I’ll be capturing my learning adventures this summer (and hopefully beyond) on this blog. My goal is for it to be a learning resource for developers who come to Android development without formal programming training.  This may morph over time. We’ll see.