开发者

Can hook methods called by the system ever be passed in a null argument reference?

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:
            c开发者_开发知识库reateNote();
            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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜