Defensive null checks

Do not do defensive null checks. If a null is encountered in a place it is not expected, a NullPointerException should be thrown.

public void addFriendToList(List<Friend> flist, Friend f) {
    if (flist != null && f != null) {
        flist.add(f);
    }   
}

In the above method, the checks for null should not be there. If someone really passes a null friends list or a null friend object, he should get a null pointer exception.

Defensive programming like the above actually can hide a lot of bugs in the calling code, so is not advised.

For a more detailed reading – Why defensive programming is rubbish

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s