0

Possible Duplicate:
Is returning null bad design?

Suppose I have a prompt asking the user to enter something. If the user does not match my specifications, the else block returns null. Is this bad practice? If so, how could I repeat the prompt within the scope of the if/else block?


    if( foo.equalsIgnoreCase( "y" ) ) {
      return bar[x][y];
    }
    else if( foo.equalsIgnoreCase( "n" ) ) {
      return bar[x++][y];
    }
    else {
      return null;
    }

Community
  • 1
  • 1
  • I recommend all readers of this question to [check the answers on the linked question](http://stackoverflow.com/questions/1274792/is-returning-null-bad-design) - I believe there is very good info there if you want to know more about why returning null in general can be considered a bad idea. – Richard Le Mesurier Jul 30 '12 at 12:33

3 Answers3

1

null is a fine value to use for this purpose. It's not a bad practice. You need to use something, and null has "not defined" semantics.

Your other option is to return what the user entered, and then test "if its not 'y' or its not 'n' then ask again", but really, thats more complicated that just testing something like !value.

Just be sure to document that your method "will return null if user does not enter 'y' or 'n'" in the javadocs.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
1

null as a return value is certainly not bad practice. Whether or not it's the right choice in your case depends on the method, and the rest of the class interface.

pb2q
  • 58,613
  • 19
  • 146
  • 147
-1

I believe it would be better to define a constant representing this 3rd option.

Your source code will be easier to read.

If you want to set it to null that's fine, but I would recommend against it, since this opens you up to the possibility of NullPointerException problems later down the line.

For this reason I consider returning null poor practice in many circumstances.

You can read more about this here: https://stackoverflow.com/a/1274822/383414 (someone flagged this question as a possible duplicate)

Community
  • 1
  • 1
Richard Le Mesurier
  • 29,432
  • 22
  • 140
  • 255
  • seriously a downvote? After posting my answer, I saw the duplicate question - the "accepted answer" there had +70 votes, and is basically what I said above (which is why I then linked across to it to emphasize)? So just wondering - why the downvote? – Richard Le Mesurier Jul 30 '12 at 12:30