github.com/jeffgbutler/practical-functional-java
These three things alone reduce quite a lot of the boilerplate code we've just been through
Java
public class Person {
private String firstName;
private String lastName;
private Person(Builder builder) {
firstName = Objects.requireNonNull(builder.firstName);
lastName = Objects.requireNonNull(builder.lastName);
this.description = description;
}
// getters, toString, equals, etc.
public static class Builder {
private String firstName;
private String lastName;
public Builder withFirstName(String firstName) {
this.firstName = firstName;
return this;
}
// etc...
}
}
Kotlin
data class Person (val firstName: String,
val lastName: String)
Every Java reference can be null. This requires a lot of null checking or Optional wrapping.
public class Person {
private Address mailingAddress;
public Address getMailingAddress() {
return mailingAddress;
}
}
public class Address {
private String secondAddresLine;
public String getSecondAddressLine() {
return secondAddresLine;
}
}
public String getSecondMailingAddress(Person person) {
if (person == null) {
return "";
}
if (person.getMailingAddress() == null) {
return "";
}
if (person.getMailingAddress().getSecondAddressLine()
== null) {
return "";
}
return person.getMailingAddress().getSecondAddressLine()
.trim();
}
Kotlin references can only be null if specifically declared to allow null
data class Person (val mailingAddress: Address?)
data class Address (val secondAddressLine: String?)
String getSecondMailingAddress(person: Person?) =
person?.mailingAddress?.secondAddressLine?.trim() ?: ""
In essence, the visitor allows adding new virtual functions to a family of classes, without modifying the classes. (wikipedia)
In the XML renderer we used the visitor pattern to add a "render" method to each of the XML model classes
Visitor is a very clever pattern, but hard to grasp
Same outcome as visitor, but far simpler to understand
data class Attribute (val name: String, val value: String)
// declare a "render" extension function
// extension functions can be in different packages,
// different JARs, different projects
fun Attribute.render(): String {
// extension methods have access non-private
// attributes and methods
// this is a Kotlin string template
return """$name="$value" """
}
val att = Attribute("foo", "bar")
val renderedString = att.render() // foo="bar"
Please rate the session. Suggestions for improvements are very welcome.
jeffgbutler@gmail.com
github.com/jeffgbutler