1

I do a middleware call as to get an array of String as shown:

String[] freqwords = MViewer.getWordNames();

The issue is that there might be no data available, so any further operations like freqWords.length, may result in NullPointerException.

So to avoid that I am handling in this below way as shown:

if (freqwords == null)
{
  freqwords = new String[0];
}

The code is working fine - please let me know if there is any better approach or any negative scenarios with this.

4
  • It's impossible to say if this is ok without looking at the rest of the related code... Commented Feb 6, 2013 at 22:36
  • 1
    Returning null arrays or collections is indeed a bad practice. Prefer returning empty arrays or collections. And prefer collections over arrays. Commented Feb 6, 2013 at 22:36
  • totally agree with you , but cant do anything with existing code . Commented Feb 6, 2013 at 22:41
  • Then wrap the method into your own, and make it return an empty array or list, like you did. Commented Feb 6, 2013 at 22:53

1 Answer 1

2

If you never need to distinguish the case of String[0] from a null return value (e.g. if null is returned if and only if there is no data available), then this seems like a perfectly reasonable solution.

Sign up to request clarification or add additional context in comments.

1 Comment

You could also end the method early if having a null freqwords means there is nothing useful to say

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.