Some notes on Elvis and Other Null-Safe Operators

Mark Mahieu markmahieu at googlemail.com
Wed Apr 15 23:40:43 PDT 2009


One more thought regarding Elvis and friends.  In the code-base I'm  
currently working on, I keep seeing code like the following:

	Map<Key, Set<Foo>> map = ...

	if (map != null) {
		Set<Foo> fooSet = map.get(key);
		if (fooSet != null) {
			for (Foo foo : fooSet) {
				...
			}
		}
	}

which can be 'simplified' in a number of ways, for example with the  
liberal sprinkling of a couple of null-transforming methods:

	Set<Foo> fooSet = emptyIfNull(map).get(key);
	for (Foo foo : emptyIfNull(fooSet)) {
		...
	}

Alternatively, with Elvis etc it could be written like this:

	for (Foo foo : map?.get(key) ?: Collections.<Foo>emptySet()) {
		...
	}

Which doesn't seem like much of an improvement, to me.  But I keep  
thinking that, in the context of this proposal, a null-safe form of  
the foreach loop might not be so bad:

	for (Foo foo :? map?.get(key)) {
		...
	}

I seem to recall that kind of example being talked about fairly  
extensively during JSR-201, but I think the discussion then was  
around whether foreach should be 'null-safe' by default.  Perhaps  
it's an example of trying to fit the proposal to the use-case, though.


Mark




More information about the coin-dev mailing list