Code Generation with tools such as Groovy, Lombok, AutoValue and Immutables will reduce boilerplate from your code and makes it more readable. An overview of creating value objects, immutability and how they do annotation processing.
6. Immutability in
plain old Java
● final
● final private
● construction in a single step
● defensive copying
● no mutators
● ...
public final class Planet {
private final double mass;
private final String name;
private final Date dateOfDiscovery;
public Planet (double mass, String mame, Date dateOfDiscovery) {
this.mass = mass;
this.name = name;
this.dateOfDiscovery = new Date(dateOfDiscovery.getTime());
}
public double getMass() {
return mass;
}
public String getName() {
return name;
}
public Date getDateOfDiscovery() {
return new Date(dateOfDiscovery.getTime());
}
}
7. Equals, hashCode
in plain-old Java
public final class Location {
private final String countryCode;
private final int priority;
public Location(String countryCode, int priority) {
this.countryCode = countryCode;
this.priority = priority;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((countryCode == null) ? 0 :
countryCode.hashCode());
result = prime * result + priority;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Location))
return false;
Location other = (Location) obj;
if (countryCode == null) {
if (other.countryCode != null)
return false;
} else if (!countryCode.equals(other.countryCode))
return false;
if (priority != other.priority)
return false;
return true;
}
}
10. And...
Dates, Cloneables and arrays are
defensively copied on the way
in (constructor) and out
(getters).
Collections and Maps are wrapped
by immutable wrapper classes.
@Immutable
import groovy.transform.Immutable
@Immutable
class Location {
String countryCode
int priority
}
17. Annotation processing
Lombok, AutoValue, and Immutables all employ annotation processing via
javac, Groovy uses groovyc
AutoValue and Immutables generate new source - which extend template class
e.g. Location.java -> AutoValue_Location.java extends Location
Groovy and Lombok modify the AST and enhances compiled class