RFR: 8305457: Implement java.io.IO [v3]

Pavel Rappo prappo at openjdk.org
Wed May 8 22:55:56 UTC 2024


On Wed, 8 May 2024 19:40:44 GMT, Stuart Marks <smarks at openjdk.org> wrote:

>>> Most of these are defined in terms of `String.valueOf(Object)` which if passed a null reference will return the String object containing `null`. So no, I don't think NPE should be thrown. It might be worth mentioning this explicitly somewhere though.
>> 
>> Right, in our current model, `Console.readln(prompt)` can be reduced to `Console.print(prompt)` followed by actual reading. `Console.print(prompt)` can in turn be reduced to printing the result of `String.valueOf((Object) prompt)`, which is a string "null".
>> 
>> The above reduction means that `Console.readln(null)` will not throw NPE. Now, what I'm asking if that's what we really want.
>> 
>> With `Console.println(null)` and `Console.print(null)` not throwing NPE makes sense. However, with `Console.readln(null)` it might not. After all, we ask for a **`String`** prompt, not an `Object` prompt. All other methods of `Console` that accept `String`, throw NPE if that string is null.
>> 
>> One more consideration. Whatever the behaviour we choose for `Console.readln(null)`, we should choose the same behaviour for `IO.readln(null)`. Otherwise, it would be a constant source of unpleasantly surprising inconsistency.
>> 
>> Thoughts?
>
> A fair question, whether to treat `readln` differently because it takes a String argument instead of an Object.
> 
> I guess I'd like to see a scheme like the following:
> 
>     String s = cons.readln(prompt);
> 
> is effectively the same as
> 
>     cons.print(prompt);
>     cons.flush();
>     String s = cons.readLine(); // note no-arg readLine() method
> 
> In other words, define `readln` to behave "as if" the other methods were called. This would end up with a null prompt argument printing "null" and not throwing NPE.
> 
> This is internally consistent, at least. Beginning programmers will eventually learn that using null will lead to NPE. It might make things easier if NPEs were kept out of this little corner of the library. That's just my guess though.
> 
> Also, recall that `String.valueOf((Object) null)` and `String.valueOf((String) null)` both result in "null". But if one were to write `String.valueOf(null)` that throws NPE, because that selects the `valueOf(char[])` overload. That's kind of the outlier. Note further that the built-in `+` string concatenation operator will also convert null references to "null".
> 
> Personally I've always hated that string conversions of null in Java often result in "null" but it's baked into the system fairly deeply, so I think we should stick with it.

Okay, I'll push a commit soon.

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/19112#discussion_r1594784225


More information about the core-libs-dev mailing list