Archives for posts with tag: Patterns

Splash screens form a very common pattern in mobile development. As simple as showing the user a beautiful logo and maybe doing some background loading may seem, I’ve seen many more flawed implementations than correct ones so far.

The Worst Possible Way

If you want to display a static layout, wait a few moments and load something else, you might be tempted to do this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);

    Thread.sleep(SPLASH_DURATION_MS);

    startActivity(this, MainActivity.class);
    finish();
}

This is absolutely horrible. The Thread.sleep() call blocks the UI thread, rendering the application unresponsive and possibly causing a force-close. This is absolutely not the way to go about it.

The Very Bad Way

To avoid blocking, you might resort to firing a thread, sleeping there, and calling runOnUiThread() to start the next Activity. This would effectively address the issue with the previous implementation. There’s no need to fire another thread just to let time go by, however. We can do better.

The Still Bad Way

Using Android’s Handler, you can post an event to the main UI loop and schedule it to run after a delay.

private Handler mHandler = new Handler();
    
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    
    mHandler.postDelayed(new Runnable() {
        public void run() {
            startActivity(new Intent(
                SplashActivity.this, MainActivity.class
            ));
            finish();
        }
    }, SPLASH_DURATION_MS);
}

Well, this is still bad, but for different reasons: even if the interface is responsive, and there’s nothing problematic going on in the code, you’re making the user wait for God knows how long on a splash screen that he might have seen a zillion times already. It’s a perfect recipe for turning “oh, cool design!” into “START already, dammit!”.

The Right Way ™

Using the Handler method described above, why don’t we let the user interrupt the wait by clicking on the splash screen? If he’s busy staring at our artwork, let him; if he’s impatient, he’ll try to click anywhere and manually skip the splash.

Let’s see the full code for that:

public class SplashActivity extends Activity {
    
    private static final int SPLASH_DURATION_MS = 2000;
    
    private Handler mHandler = new Handler();
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        
        mHandler.postDelayed(mEndSplash, SPLASH_DURATION_MS);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mEndSplash.run();
        return super.onTouchEvent(event);
    }
    
    private Runnable mEndSplash = new Runnable() {
        public void run() {
            if (!isFinishing()) {
                mHandler.removeCallbacks(this);

                startActivity(new Intent(
                    SplashActivity.this, MainActivity.class
                ));

                finish();
            }
        };
    };
}

Not so simple as Thread.sleep(), I admit, but correctly implemented and completely copy-pastable.

I’ve seen a lot of confusion on how to correctly create headers and footers in Activities with a ScrollView root. There’s also a lot of bad advice lying around, mostly involving RelativeLayout and resulting in headers and footers overlapping other parts of the UI when space is scarce.

We’ll take a look at a better solution using the much more simple LinearLayout.

To be on the same page, let’s agree on how we want our footers and/or headers to behave. First, however, some definitions. Our content, hosted inside a fullscreen ScrollView, will consist of:

  • Header (optional): this View‘s top will match the ScrollView‘s.
  • Body: this View will always be right below the header, and somewhere above the footer.
  • Footer (optional): this View‘s bottom will match the ScrollView‘s

Good! Now, when the body’s content is smaller than the remaining space between the header and the footer, the layout will look like this:

Layout with no scrollbars

Layout with no scrollbars.

Unlike simple fixed headers and footers, however, ours will move out of the way if necessary. If the body’s size exceeds the available space, we want the layout to behave like this:

Layout with scrollbars

Layout with scrollbars. Left: scrolled to top; right: scrolled to bottom

Notice how, now that the screen’s size is not enough to display all of our content, the footer and the header are no longer anchored and respond to scrolling, without overlapping the body.

So, how do we get there? We use LinearLayout‘s layout_weight behavior to ensure that the body area will always expand to be at least as long as the remaining sandwiched space between the header and the footer. If the content’s shorter, it expands until it reaches the footer’s top; if it’s longer, it pushes the footer down.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!-- HEADER -->
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
    />

    <!-- BODY -->
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:orientation="vertical"
    />

    <!-- FOOTER -->
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
    />
</LinearLayout>
</ScrollView>

VoilĂ !

Obviously, the header and the footer can be omitted. They are not both mandatory, the same technique will work for just a header, or just a footer.

If you’ve read this far, well, I hope this helped you. You are more than welcome to contact me with doubts, suggestions or corrections.

Saludos!

How’s that for a catchy title, huh? Let me take a moment to re-read it. Done. Moving on, then.

I’ve been digging around GitHub and GoogleCode a lot lately. I’ve probably seen more of other people’s code this past month that in the year before that, and specially Java code, for obvious reasons.

Among OOP languages, Java is specially infamous for its average code quality and readability. I won’t argue with that: expressing certain kinds of behavior in Java through code that won’t offend the eyes of a reader is already quite a challenge, and that’s if you actually care. Lots of coders don’t. However, I noticed a peculiar trend I consider particularly dangerous, a trend not restricted to but much more frequent in Java, and thought I’d write a short post about it.

Getters, getters

Let’s say we start writing a class. In a sudden fit of originality, let’s call it Person, and create some of the members we’ll need — say id, name, birthDate and address.

class Person {

    private long id;
    private Date birthDate;
    private String name, address;

}

Since we’re are educated object-oriented programmers, we declare these fields to be private, and create accessors for them: getId() getName(), getAddress() and getBirthDate().

Now, we notice that most of the time we just want the person’s age, rather than its date of birth. Well, thanks to our encapsulation, we can offer that through the public interface without changing our internal data structure. Oh, and while we’re at it, we can also wrap the ugly java.util.Date into JodaTime’s superior DateTime to perform the calculation!

public int getAge() {
    Date now = new Date();

    /* Mmmh,... maybe I should make this blog's content column wider */
    return Years.yearsBetween(
        new DateTime(birthDate),
        new DateTime(now)

    ).getYears();
}

This last bit of code may seem trivial enough, but think about the amazing encapsulation it achieves! The user of this class is totally unaware of how we handle our data, he just interacts with our Person and obtains its age as fast as he can call a getter. He doesn’t need to know that to return that integer we created and discarded at least four objects, and did some math — that’s what encapsulation is about, right?

We then close the editor tab, satisfied with our beautiful OO implementation.

Some time later, another coder (let’s call him John — there’s just no end to my creativity today!) is asked to sort a list of Person instances by age. He saw our getter used somewhere else in the code, so he thinks “oh, good! I’ll just write a Comparator!”.

public class AgeComparator implements Comparator<Person> {

    @Override
    public int compare(Person p1, Person p2) {
        return p1.getAge() - p2.getAge();
    }

}

And, armed with the Comparator, he sets off to sort a list of millions of people and spends half an afternoon wondering just why the Garbage Collector is working so much overtime.

The getter anti-pattern

Okay, I admit I could’ve come up with a better example, but you’re looking at a guy that named his class Person and his coder John. Let’s just pretend you are shocked by the sheer impact the previous section had on you, and move on to see why poor John wasted so much of his time.

I don’t think it’s our fault for storing a person’s date of birth, instead of his/her age. We are allowed to compute, aren’t we? We can’t just have a variable for every derived attribute out there, or the data redundancy would quickly get out of hand. No, I think the problem is in the following snippet:

    public int getAge();

Yes. The problem is we named the method getAge(). We could’ve named it calculateAge(), and John would’ve been much more careful, instead of instantly assuming the operation was as light-weight as returning an instance member.

I’ve seen getters perform all kinds of monstrous computations. I’ve seen classes with nothing but getters, half of them false accessors in disguise. I’ve even been fooled several times myself into using a getter that seemed innocent enough only to later discover it was doing all sorts of operations behind my back. I don’t just think this particular abuse of getters is bad, I think it qualifies as an anti-pattern by definition:

  • It initially appears to be beneficial, since getters go a long way towards hiding internal details, but ultimately produces more bad consequences than beneficial results, for abusing them lures users of your code into believing everything is easily accessible.
  • An alternative solution exists: just choose a different name.

There are thousands of verbs other than getcalculate, compute, build, create,… — and if my creativity can come up with four today, so can yours anytime.

All that, or maybe I’m just exaggerating. I do that. Have a nice week!