mkodekar / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Allowing null Splitter#split(Charsequence cs) arguments without NPE #1866

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Currently, when calling Splitter#split(CharSequence cs) or 
splitToList(CharSequence cs), if cs is null, then an NPE is thrown.

Can you add an option to not throw an NPE?

I can see many ways of doing this.  In descending order of preference:

1)
Add a modifier method:

forNullInputReturn(List<String> nullInputList)

2)
Add a modifier method:

forNullInputReturn(Splitter.ForNullInputReturn nullInput)

where Splitter.ForNullInputReturn is an enum with values:

EMPTY_LIST
SINGLETON_LIST_EMPTY_STRING
etc.

3)
Add two modifier methods:

forNullInputReturnSingleton()
returns the equivalent of Collections.singletonList("")

forNullInputReturnEmpty()
returns the equivalent of Collections.emptyList()

4)
Add a modifier method:

treatNullInputAsEmptyString().

When split(null) is called on a Splitter returned by 
treatNullInputAsEmptyString(), it will:

a) return an empty Iterable<String>, if omitEmptyStrings() has also been called 
on the Spiltter

b) return an Iterable<String> containing only a single element (whose value is 
""), if omitEmptyStrings() has NOT been called on the Spiltter

Thanks.

Original issue reported on code.google.com by ross.gol...@gmail.com on 18 Oct 2014 at 7:47

GoogleCodeExporter commented 9 years ago
https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Con
venience_methods

Guava consistently rejects nulls in every API were passing in a null is likely 
to represent a bug.  It seems as though you are trying to conflate null with 
the empty string, which is a serious code smell.  The link above suggests 
several ways of dealing with that, however.

Original comment by lowas...@google.com on 18 Oct 2014 at 7:56

GoogleCodeExporter commented 9 years ago
I agree with what Louis said.

In your specific case, you probably just want to wrap your CharSequence in a 
call to Strings.nullToEmpty(charSeq).

Original comment by kak@google.com on 18 Oct 2014 at 1:14

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<issue id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:08

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:07