SlideShare a Scribd company logo
1 of 27
Download to read offline
Writing beautiful code
with Java 8
sergiu.indrie@iquestgroup.com
Disclaimer
This is not a clean code presentation, but rather a code esthetics oriented
presentation which may include clean code.
Beautiful code?
● Easy to read/understand/write
● Concise
● DSL-like
● Clean code ++
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);
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();
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);
}
Ugly vs Beautiful
// guarded logging
if (logger.isDebugEnabled()) {
logger.debug("This {} and {} with {} ", 1, that, compute());
}
VS
logger.debug("This {} ", () -> compute());
What’s “new” in Java 8?
● Lambdas
Runnable r2 = () -> System.out.println("Hello world two!");
● Streams
List<Room> rooms = microsoftExchangeService.getRoomLists().getItems().parallelStream()
.filter(this::isValidRoomList)
.map(this::retrieveRoomsInRoomList)
.flatMap(List::stream)
.collect(Collectors.toList());
● Optional
Optional<Meeting> meeting = meetingsDao.findById(meetingId);
meeting.ifPresent(this::setMeetingAsManuallyEnded);
PS - Help from IDEA
● Migration suggestions (more to come in IDEA 2016.3)
Enemy #1: Checked Exceptions
private static void checkedException() {
List<String> strings = Arrays.asList(1, 2, 3, 4, 5).stream()
.map(Exceptions::intToString)
.collect(Collectors.toList());
System.out.println(strings);
}
private static String intToString(Integer number) throws Exception {
if (number == 3) {
throw new Exception("wrong number, pal!");
}
return String.valueOf(number);
}
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?
Enemy #1: Checked Exceptions - Solution
● 1st Solution - Unchecked Exceptions*
● 2nd Solution - Wrap to 1st (see org.jooq.lambda.Unchecked)
public static <T> T unchecked(Callable<T> callable) {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
List<Room> rooms = roomAddresses.parallelStream()
.map(room -> unchecked(() -> getRoomWithoutMeetings(room)))
.collect(Collectors.toList());
* Python, Scala, C#, Ruby, PHP … don’t have checked exceptions
Enemy #1: Checked Exceptions - Solution
public static <T> T unchecked(Callable<T> callable) {
try {
return callable.call();
} catch (ApiServiceException e) {
throw new ApiServiceRuntimeException(e);
} catch (Exception e) {
throw runtime(e);
}
}
private static RuntimeException runtime(Throwable e) {
if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException(e);
}
Enemy #1: Checked Exceptions - Solution
● A more functional approach
Enemy #1: Checked Exceptions - Solution
● A more functional approach
String complexResult = Try.of(SomeClass::dangerousGet)
.recover(x -> Match(x).of(
Case(instanceOf(IllegalStateException.class), () -> "1st exception"),
Case(instanceOf(IllegalArgumentException.class), () -> "2nd exception")
))
.getOrElse("default2");
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
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());
Java 8 is nice, but
Java 8 Computation Style
Level up: Javaslang
// Java 8
List<Integer> integers = Arrays.asList(1, 2, 3, 4);
List<Integer> evenNumbers = integers.stream()
.filter(nr -> nr % 2 == 0)
.collect(Collectors.toList());
// Javaslang
List<Integer> integers = List.of(1, 2, 3, 4);
List<Integer> evenIntegers = integers.filter(nr -> nr % 2 == 0);
* javaslang.collection.List
Level up: Javaslang
● “...greatly inspired by Scala”
● Hence very functional
● facilitates functional programming through immutability
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
● Functional exception handling
// no need to handle exceptions
Try.of(SomeClass::bunchOfWork).getOrElse("default");
String complexResult = Try.of(SomeClass::dangerousGet)
.recover(x -> Match(x).of(
Case(instanceOf(IllegalStateException.class), () -> "1st exception"),
Case(instanceOf(IllegalArgumentException.class), () -> "2nd exception")
))
.getOrElse("default2");
Level up: Javaslang
● Lazy
Lazy<Double> lazy = Lazy.of(Math::random);
lazy.isEvaluated(); // = false
lazy.get(); // = 0.123 (random generated)
lazy.isEvaluated(); // = true
lazy.get(); // = 0.123 (memoized)
● + other FP features like function composition, currying, memoization, lifting,
immutable collections, tuples
Level up: Javaslang
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.
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)
}
References
https://github.com/tedyoung/awesome-java8
https://blog.jooq.org/2014/05/02/java-8-friday-lets-deprecate-those-legacy-libs/
https://blog.jetbrains.com/idea/2016/07/java-8-top-tips/
http://blog.agiledeveloper.com/2015/06/lambdas-are-glue-code.html
https://garygregory.wordpress.com/2015/09/16/a-gentle-introduction-to-the-log4j-api-and-lambda-basics/
https://dzone.com/articles/java-8-functional-interfaces-0
http://openjdk.java.net/jeps/269
https://blogs.oracle.com/briangoetz/entry/exception_transparency_in_java
http://www.artima.com/intv/handcuffs.html
http://www.mindview.net/Etc/Discussions/CheckedExceptions
https://github.com/jOOQ/jOOL#orgjooqlambdaunchecked
http://iteratrlearning.com/java9/2016/08/06/java9-streams.html
http://www.javaslang.io/
http://www.scala-lang.org/
That’s all folks!

More Related Content

What's hot

Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in ScalaRadim Pavlicek
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Trisha Gee
 
Java simple programs
Java simple programsJava simple programs
Java simple programsVEERA RAGAVAN
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Susan Potter
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diplomamustkeem khan
 
02 Java Language And OOP PART II
02 Java Language And OOP PART II02 Java Language And OOP PART II
02 Java Language And OOP PART IIHari Christian
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 

What's hot (19)

Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Java programs
Java programsJava programs
Java programs
 
Java programs
Java programsJava programs
Java programs
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Templates
TemplatesTemplates
Templates
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Java generics
Java genericsJava generics
Java generics
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
 
02 Java Language And OOP PART II
02 Java Language And OOP PART II02 Java Language And OOP PART II
02 Java Language And OOP PART II
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 

Viewers also liked

2 buffer overflows
2 buffer overflows2 buffer overflows
2 buffer overflowsKarthic Rao
 
Clean Code - How to write comprehensible code regarding cognitive abilities o...
Clean Code - How to write comprehensible code regarding cognitive abilities o...Clean Code - How to write comprehensible code regarding cognitive abilities o...
Clean Code - How to write comprehensible code regarding cognitive abilities o...Mario Gleichmann
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
Redis training for java software engineers
Redis training for java software engineersRedis training for java software engineers
Redis training for java software engineersMoshe Kaplan
 
Empathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible codeEmpathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible codeMario Gleichmann
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)jmiguel rodriguez
 
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...Nikita Koksharov
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Performance Tuning EC2 Instances
Performance Tuning EC2 InstancesPerformance Tuning EC2 Instances
Performance Tuning EC2 InstancesBrendan Gregg
 

Viewers also liked (16)

2 buffer overflows
2 buffer overflows2 buffer overflows
2 buffer overflows
 
Clean Code - How to write comprehensible code regarding cognitive abilities o...
Clean Code - How to write comprehensible code regarding cognitive abilities o...Clean Code - How to write comprehensible code regarding cognitive abilities o...
Clean Code - How to write comprehensible code regarding cognitive abilities o...
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Redis training for java software engineers
Redis training for java software engineersRedis training for java software engineers
Redis training for java software engineers
 
Empathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible codeEmpathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible code
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)
 
Clean Code
Clean CodeClean Code
Clean Code
 
OOP Basics
OOP BasicsOOP Basics
OOP Basics
 
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
Java data structures powered by Redis. Introduction to Redisson @ Redis Light...
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Clean code
Clean codeClean code
Clean code
 
Performance Tuning EC2 Instances
Performance Tuning EC2 InstancesPerformance Tuning EC2 Instances
Performance Tuning EC2 Instances
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Build Features, Not Apps
Build Features, Not AppsBuild Features, Not Apps
Build Features, Not Apps
 

Similar to Writing beautiful code with Java 8

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Pure function And Functional Error Handling
Pure function And Functional Error HandlingPure function And Functional Error Handling
Pure function And Functional Error HandlingGyooha Kim
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalUrs Peter
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language EnhancementsYuriy Bondaruk
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 

Similar to Writing beautiful code with Java 8 (20)

What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Pure function And Functional Error Handling
Pure function And Functional Error HandlingPure function And Functional Error Handling
Pure function And Functional Error Handling
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 

Recently uploaded

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 

Recently uploaded (20)

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 

Writing beautiful code with Java 8

  • 1. Writing beautiful code with Java 8 sergiu.indrie@iquestgroup.com
  • 2. Disclaimer This is not a clean code presentation, but rather a code esthetics oriented presentation which may include clean code.
  • 3. Beautiful code? ● Easy to read/understand/write ● Concise ● DSL-like ● Clean code ++
  • 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());
  • 8. What’s “new” in Java 8? ● Lambdas Runnable r2 = () -> System.out.println("Hello world two!"); ● Streams List<Room> rooms = microsoftExchangeService.getRoomLists().getItems().parallelStream() .filter(this::isValidRoomList) .map(this::retrieveRoomsInRoomList) .flatMap(List::stream) .collect(Collectors.toList()); ● Optional Optional<Meeting> meeting = meetingsDao.findById(meetingId); meeting.ifPresent(this::setMeetingAsManuallyEnded);
  • 9. PS - Help from IDEA ● Migration suggestions (more to come in IDEA 2016.3)
  • 10. Enemy #1: Checked Exceptions private static void checkedException() { List<String> strings = Arrays.asList(1, 2, 3, 4, 5).stream() .map(Exceptions::intToString) .collect(Collectors.toList()); System.out.println(strings); } private static String intToString(Integer number) throws Exception { if (number == 3) { throw new Exception("wrong number, pal!"); } return String.valueOf(number); }
  • 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?
  • 12. Enemy #1: Checked Exceptions - Solution ● 1st Solution - Unchecked Exceptions* ● 2nd Solution - Wrap to 1st (see org.jooq.lambda.Unchecked) public static <T> T unchecked(Callable<T> callable) { try { return callable.call(); } catch (Exception e) { throw new RuntimeException(e); } } List<Room> rooms = roomAddresses.parallelStream() .map(room -> unchecked(() -> getRoomWithoutMeetings(room))) .collect(Collectors.toList()); * Python, Scala, C#, Ruby, PHP … don’t have checked exceptions
  • 13. Enemy #1: Checked Exceptions - Solution public static <T> T unchecked(Callable<T> callable) { try { return callable.call(); } catch (ApiServiceException e) { throw new ApiServiceRuntimeException(e); } catch (Exception e) { throw runtime(e); } } private static RuntimeException runtime(Throwable e) { if (e instanceof RuntimeException) { return (RuntimeException) e; } return new RuntimeException(e); }
  • 14. Enemy #1: Checked Exceptions - Solution ● A more functional approach
  • 15. Enemy #1: Checked Exceptions - Solution ● A more functional approach String complexResult = Try.of(SomeClass::dangerousGet) .recover(x -> Match(x).of( Case(instanceOf(IllegalStateException.class), () -> "1st exception"), Case(instanceOf(IllegalArgumentException.class), () -> "2nd exception") )) .getOrElse("default2");
  • 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());
  • 18. Java 8 is nice, but Java 8 Computation Style
  • 19. Level up: Javaslang // Java 8 List<Integer> integers = Arrays.asList(1, 2, 3, 4); List<Integer> evenNumbers = integers.stream() .filter(nr -> nr % 2 == 0) .collect(Collectors.toList()); // Javaslang List<Integer> integers = List.of(1, 2, 3, 4); List<Integer> evenIntegers = integers.filter(nr -> nr % 2 == 0); * javaslang.collection.List
  • 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
  • 22. ● Functional exception handling // no need to handle exceptions Try.of(SomeClass::bunchOfWork).getOrElse("default"); String complexResult = Try.of(SomeClass::dangerousGet) .recover(x -> Match(x).of( Case(instanceOf(IllegalStateException.class), () -> "1st exception"), Case(instanceOf(IllegalArgumentException.class), () -> "2nd exception") )) .getOrElse("default2"); Level up: Javaslang
  • 23. ● Lazy Lazy<Double> lazy = Lazy.of(Math::random); lazy.isEvaluated(); // = false lazy.get(); // = 0.123 (random generated) lazy.isEvaluated(); // = true lazy.get(); // = 0.123 (memoized) ● + other FP features like function composition, currying, memoization, lifting, immutable collections, tuples 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) }