2014-10-09

There is an Elvis in Java, kind of - but you should still obey the Law Of Demeter

Languages such as Groovy have an Elvis operator which helps you to avoid tedious checking possible null-references when navigating through objects, like those:

public class Gear {
private Collection<Object> parts;

public Collection<Object> getParts() {
   return parts;
}

public void setParts(Collection<Object> parts) {
   this.parts = parts;
}
}

public class Car {
private Gear gear;

public Gear getGear() {
   return gear;
}

public void setGear(Gear gear) {
   this.gear = gear;
}        
}

Elvis works as follows:

Car car = new Car();
Collection<Object>> partsOrNot = car?.getGear()?.getParts(); // No NPE, but null assigned!

In Java there is no strict language construct like Elvis operator, but sill Java introduces Optional which can help you alleviate the same problems as the mentioned operator:

Optional<Car> optionalCar = Optional.of( new Car());
Optional<Collection<Object>> partsOrNot =
       optionalCar
               .map(Car::getGear)
               .map(Gear::getParts);

Similarities between Elvis and Optional.map(...) method are pretty strong, although the latter is based on Lambda expression and not language syntax and because of that it introduces a little more clutter to the solution.
So, no - there is no Elvis operator in Java. And yes - there is a notion of Elvis operator in Java, pretty much powerful one.

But there is a catch. We still should be tied to clean code and some ground programming rules. One of them is the Law of Demeter:

Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. Or: Each unit should only talk to its friends; Don’t talk to strangers.

Surely, the Elvis operator is the mechanism which encourages breaking this law. And the Optional.map does the same thing. They both introduce strong coupling between objects and as such, they both should be avoided, despite the language (Elvis in languages that support it and Optional.map in Java).

Although the concept of Elvis operator helps to overcome the boilerplate checking code it is still the code smell hidden in syntactic sugar. And the Optional.map with method chaining do the same thing.

I like Java for its feature balance and I think that there is no need to introduce the native Elvis operator to the language because it offers sufficient solution for situations we should avoid nevertheless.

No comments:

Post a Comment