Java 8 helps use write better looking code. Checked exceptions, however, do not. What can we do to overcome these issues?
Lambdas and streams help us write clear and concise code, but can we do better? Javaslang helps out a bit.
Want more? Maybe turn to Scala.
4. Ugly vs Beautiful
for (int i = 0; i < meetings.size(); i++) {
System.out.println(meetings);
}
for (Meeting meeting : meetings) {
System.out.println(meeting);
}
meetings.forEach(System.out::println);
5. Ugly vs Beautiful
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Complex stuff");
}
}).start();
new Thread(() -> System.out.println("Complex stuff")).start();
6. Ugly vs Beautiful
Map<String, List<Meeting>> meetingsById = meetings.stream()
.collect(Collectors.groupingBy(Meeting::getId));
Map<String, List<Meeting>> meetingsGrouped = new HashMap<>();
for (Meeting meeting : meetings) {
if (!meetingsGrouped.containsKey(meeting.getId())) {
meetingsGrouped.put(meeting.getId(), new ArrayList<>());
}
meetingsGrouped.get(meeting.getId()).add(meeting);
}
7. Ugly vs Beautiful
// guarded logging
if (logger.isDebugEnabled()) {
logger.debug("This {} and {} with {} ", 1, that, compute());
}
VS
logger.debug("This {} ", () -> compute());
11. Enemy #1: Checked Exceptions
● Complex issue (see Brian Goetz’s post from 2010)
○ generic type parameters are monadic ⇒ one exact type
○ throws clauses are variadic ⇒ 0 or more types
● Solution?
16. By the way
Java 9 brings: Collection Factory Methods* (all immutable)
+ some stream improvements like iterate, take/dropWhile
* Nevermind if you’ve been using Guava, jOOQ
17. Java 8 is nice, but don’t
// long lambdas
numbers.forEach(e -> {
int count = 0;
for(int i = 1; i <= e; i++) {
if(e % i == 0) count++;
}
System.out.println(count);
});
// unformatted streams
List<String> strings = Arrays.asList(1, 2, 3).stream().map(Object::toString)
.map(String::toUpperCase).limit(5).collect(Collectors.toList());
20. Level up: Javaslang
● “...greatly inspired by Scala”
● Hence very functional
● facilitates functional programming through immutability
21. List<Integer> integers = Arrays.asList(1, 2, 3, 4);
● List is really javaslang.collection.List :) but we do have toJavaList/Array/Collection/Set() etc.
public interface List<T> extends Kind1<List<?>, T>, LinearSeq<T>, Stack<T> {
default java.util.List<T> toJavaList() {
return ValueModule.toJavaCollection(this, new ArrayList<>());
}
● All Javaslang collections are Iterable and thus can be used in enhanced for-statements
for (String s : List.of("Java", "Advent")) {
// side effects and mutation
}
Level up: Javaslang
24. Or maybe just switch to Scala :D
// type inference, nice constructors, native streams API, no semicolons :)
val integers = List(1, 2, 3, 4)
val evenIntegers = integers.filter(_ % 2 == 0)
// pre/post/infix operators
val sum = (1 to 10).sum
// immutable, generated equals/getter/toString/hashcode, pattern matching decomposition
case class Person(firstName: String, lastName: String)
object Singleton {}
// immutable collections, XML processing, multiple inheritance, tuples, REPL etc.
25. Or maybe just switch to Scala :D
// pattern matching & decomposition
object Demo {
def main(args: Array[String]) {
val alice = new Person("Alice", 25)
val charlie = new Person("Charlie", 32)
for (person <- List(alice, charlie)) {
person match {
case Person("Alice", 25) => println("Hi Alice!")
case Person(name, age) => println(
"Age: " + age + " year, name: " + name + "?")
}
}
}
case class Person(name: String, age: Int)
}