tags:

views:

20

answers:

1

While doing normal day-to-day Android development, is it safe to assume that hook methods called by the system will not pass in invalid references (ex.: null), or should I always be double-checking what arguments get passed in?

For example, can the method onOptionsItemSelected(MenuItem) ever have a null MenuItem reference passed into it?

The reason I ask is because I was working on the Notepad 1 tutorial, and the tutorial asked me to set up a switch statement like this ...

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case INSERT_ID:
            createNote();
            return true;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

I started wondering if I should be testing if item is null before making a getItemId() method call on it, or just trust the system to not ever pass me a null?

I don't want to make my code slower by doing null checks when I shouldn't be worried about that happening, etc.

+1  A: 

Having a null check on an option being selected does not sound like an often enough call that would noticeably slow or bloat the code. I can imagine a null being passed if the menu item disappeared before being handled by the hook but I doubt that would happen so I suppose don't bother with the null check if speed is really a concern.

Rob Olmos
Thanks for the answer. ¶ Well, speed doesn't mean much if I'm throwing an exception. If its possible for the system to pass in a null, its probably better to test for nulls. ¶ I was basically wondering if the system itself would throw a null when it has a null reference and before it would pass the null on to my code. ¶ Being new to Android coding (Java Swing here) I'm trying to be mindful of coding in a limited resources environment. May be over thinking it though.
Adrian Romanelli