SlideShare a Scribd company logo
1 of 35
Download to read offline
SOLID mit Java 8
Java Forum Stuttgart 2016
Roland Mast
Sybit GmbH
Agiler Software-Architekt
Scrum Master
roland.mast@sybit.de
Roland Mast
Sybit GmbH
Agiler Software-Architekt
roland.mast@sybit.de
5 Principles
• Single responsibility
• Open Closed
• Liskov Substitution
• Interface Segregation
• Dependency Inversion
SOLID und Uncle Bob
Single Responsibility
Principle?
Single Responsibility
Principle?
A class should have
one, and only one,
reason to change.
A class should have
one, and only one,
reason to change.
// Strings in einem Array nach deren Länge sortieren
Arrays.sort(strings, new Comparator<String>() {
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
});
Arrays.sort(strings, (a, b) -> Integer.compare(a.length(), b.length()));
// Strings alphabetisch sortieren
Arrays.sort(strings, String::compareToIgnoreCase);
Lambdas
List<Person> persons = Arrays.asList(
// name, age, size
new Person("Max", 18, 1.9),
new Person("Peter", 23, 1.8),
new Person("Pamela", 23, 1.6),
new Person("David", 12, 1.5));
Double averageSize = persons
.stream()
.filter(p -> p.age >= 18)
.collect(Collectors.averagingDouble(p -> p.size));
Lambdas in Streams
Iteration über
die Daten
Filtern anstatt
if (age >= 18) {
keep();
}
Collectors berechnet
den Durchschnitt
Single Responsibility
public interface BinaryOperation {
long identity();
long binaryOperator(long a, long b);
}
public class Sum implements BinaryOperation {
@Override
public long identity() { return 0L; }
@Override
public long binaryOperator(long a, long b) {
return a + b;
}
}
Single Responsibility
private long[] data;
public long solve() {
int threadCount = Runtime.getRuntime().availableProcessors();
ForkJoinPool pool = new ForkJoinPool(threadCount);
pool.invoke(this);
return res;
}
protected void compute() {
if (data.length == 1) {
res=operation.binaryOperator(operation.identity(), data[0]);
} else {
int midpoint = data.length / 2;
long[] l1 = Arrays.copyOfRange(data, 0, midpoint);
long[] l2 = Arrays.copyOfRange(data, midpoint, data.length);
SolverJ7 s1 = new SolverJ7(l1, operation);
SolverJ7 s2 = new SolverJ7(l2, operation);
ForkJoinTask.invokeAll(s1, s2);
res = operation.binaryOperator(s1.res, s2.res);
}
}
Daten müssen
selbst aufgeteilt und
zusammengeführt
werden
Interface
und Klasse
definieren
Operation
Parallele Summenberechnung
Threadpool muss selbst
erzeugt werden
private long[] data;
public long sumUp() {
return LongStream.of(data)
.parallel()
.reduce(0, (a, b) -> a + b);
}
Parallel ReduceSingle Responsibility
Single Responsibility Principle
Lambdas + Streams
Kapseln Verantwortlichkeiten
Open/Closed
Principle?
Open/Closed
Principle?
You should be able to
extend a classes
behavior, without
modifying it.
You should be able to
extend a classes
behavior, without
modifying it.
public interface Iterable<T> {
Iterator<T> iterator();
}
Iterable Interface
public interface Iterable<T> {
Iterator<T> iterator();
void forEach(Consumer<? super T> action);
Spliterator<T> spliterator();
}
Open/Closed
public interface Iterable<T> {
Iterator<T> iterator();
default void forEach(Consumer<? super T> action) {
for (T t : this) { action.accept(t); }
}
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}
Default-ImplementationOpen/Closed
Open/Closed Principle
Default-Implementierungen in Interfaces
Flexibel Frameworks erweitern
Liskov's Substitution
Principle?
Liskov's Substitution
Principle?
“No new exceptions should be thrown by methods of the subtype,
except where those exceptions are themselves subtypes of exceptions
thrown by the methods of the supertype.”
Derived classes must
be substitutable for
their base classes.
Derived classes must
be substitutable for
their base classes.
/**
* Find the first occurrence of a text in files
* given by a list of file names.
*/
public Optional<String> findFirst(
String text, List<String> fileNames) {
return fileNames.stream()
.map(name -> Paths.get(name))
.flatMap(path -> Files.lines(path))
.filter(s -> s.contains(text))
.findFirst();
}
Checked Exception in StreamsLiskov‘s Substitution
public final class Files {
public static Stream<String> lines(Path path)
throws IOException {
BufferedReader br =
Files.newBufferedReader(path);
try {
return br.lines()
.onClose(asUncheckedRunnable(br));
} catch (Error|RuntimeException e) {
….. 8< ……………………
br.close();
….. 8< ……………………
}
}
IOException
/**
* Find the first occurrence of a text in files
* given by a list of file names.
*/
public Optional<String> findFirst(
String text, List<String> fileNames) {
return fileNames.stream()
.map(name -> Paths.get(name))
.flatMap(path -> mylines(path))
.filter(s -> s.contains(text))
.findFirst();
}
Handle IOExceptionLiskov‘s Substitution
private Stream<String> mylines(Path path){
try (BufferedReader br =
Files.newBufferedReader(path)) {
return br.lines()
.onClose(asUncheckedRunnable(br));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static Runnable asUncheckedRunnable(Closeable c) {
return () -> {
try {
c.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
Close StreamLiskov‘s Substitution
java.io.BufferedReader::lines +
java.nio.file.Files::find, lines, list, walk
werfen UncheckedIOException beim Zugriff innerhalb des Streams
Liskov´s Substitution Principle
Files + BufferedReader
UncheckedIOException nur bei neuen Methoden
Interface Segregation
Principle?
Interface Segregation
Principle?
Make fine grained
interfaces that are
client specific.
Make fine grained
interfaces that are
client specific.
public interface ParserContext {
Reader getReader();
void handleLine(String line);
void handleException(Exception e);
}
public void parse(final ParserContext context) {
try (BufferedReader br = new BufferedReader(context.getReader())) {
String line;
do {
line = br.readLine();
if (line != null) { context.handleLine(line); }
} while (line != null)
} catch (IOException e) { context.handleException(e); }
}
InterfacesInterface Segregation
1 Interface mit
3 Methoden
<T> T withLinesOf(Supplier<Reader> reader,
Function<Stream<String>, T> handleLines,
Function<Exception, RuntimeException> transformException) {
try (BufferedReader br = new BufferedReader(reader.get())) {
return handleLines.apply(br.lines());
} catch (IOException e) {
throw transformException.apply(e);
}
}
Functional InterfacesInterface Segregation
3 separate
Interfaces
withLinesOf(
() -> reader,
lines -> lines
.filter(line -> line.contains("ERROR"))
.map(line -> line.split(":")[1])
.collect(toList()),
LogAnalyseException::new);
Functional InterfacesInterface Segregation
LocalTimeInterface Segregation
Interface Segregation Principle
Functional Interfaces
Ermutigen zum Auftrennen von Interfaces
Dependency Inversion
Principle?
Dependency Inversion
Principle?
Depend on abstractions,
not on concretions.
Depend on abstractions,
not on concretions.
Warning: JDK internal APIs are unsupported and
private to JDK implementation that are
subject to be removed or changed incompatibly
and could break your application.
Please modify your code to eliminate
dependency on any JDK internal APIs.
For the most recent update on JDK internal API
replacements, please check:
https://wiki.openjdk.java.net/display/JDK8/Jav
a+Dependency+Analysis+Tool
jdeps -jdkinternalsDependency Inversion
jdeps -jdkinternals classes
classes -> C:Program FilesJavajdk1.8.0_74jrelibrt.jar
de.sybit.warranty.facade.impl.DefaultWarrantyFacade (classes)
-> com.sun.xml.internal.fastinfoset.stax.events.Util
JDK internal API (rt.jar)
jdepsDependency Inversion
return (Util.isEmptyString(param) || "*".equals(param));
public List<String> filterError(Reader reader) {
try (BufferedReader br =new BufferedReader(reader)){
return br.lines()
.filter(line -> line.contains("ERROR"))
.map(line -> line.split(":")[1])
.collect(toList());
} catch (IOException e) {
throw new LogAnalyseException(e);
}
}
LambdasDependency Inversion
Filterimplementierung ist
abhängig von konkreten
Implementierungen
private Parser parser = new Parser();
public List<String> filterError(Reader reader) {
return parser.withLinesOf(
reader,
lines -> lines
.filter(line -> line.contains("ERROR"))
.map(line -> line.split(":")[1])
.collect(toList()),
LogAnalyseException::new);
}
LambdasDependency Inversion
filterError() ist nur
noch abhängig von
Abstraktionen
public class Parser {
<T> T withLinesOf(Reader reader,
Function<Stream<String>, T> handleLines,
Function<Exception, RuntimeException> onError) {
try (BufferedReader br = new BufferedReader(reader)) {
return handleLines.apply(br.lines());
} catch (IOException e) {
throw onError.apply(e);
}
}
}
LambdasDependency Inversion
withLinesOf()
kapselt die
Abhängigkeiten
Dependency Inversion Principle
Lambdas
Sind starke Abstraktionen
module MyClient {
requires MyService;
}
module MyService {
exports de.sybit.myservice;
}
SOLID mit Java 9 - Jigsaw
“The principles of software design still apply, regardless
of your programming style. The fact that you've decided
to use a [functional] language that doesn't have an
assignment operator does not mean that you can ignore
the Single Responsibility Principle; or that the Open
Closed Principle is somehow automatic.”
Robert C. Martin: OO vs FP (24 November 2014)
http://blog.cleancoder.com/uncle-bob/2014/11/24/FPvsOO.html
SOLID mit Java – OO vs FP
Roland Mast, Sybit GmbH
Agiler Software-Architekt
roland.mast@sybit.de

More Related Content

What's hot

Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 

What's hot (20)

Java interface
Java interfaceJava interface
Java interface
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and Annotations
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Java generics
Java genericsJava generics
Java generics
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner Walkthrough
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Java8 - Interfaces, evolved
Java8 - Interfaces, evolvedJava8 - Interfaces, evolved
Java8 - Interfaces, evolved
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid Deconstruction
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVM
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 

Viewers also liked

Presentation CentOS
Presentation CentOS Presentation CentOS
Presentation CentOS
rommel gavia
 

Viewers also liked (10)

SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in Java
 
SOLID design principles applied in Java
SOLID design principles applied in JavaSOLID design principles applied in Java
SOLID design principles applied in Java
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
 
Robert martin
Robert martinRobert martin
Robert martin
 
Java Code Quality Tools
Java Code Quality ToolsJava Code Quality Tools
Java Code Quality Tools
 
SOLID Principles of Refactoring Presentation - Inland Empire User Group
SOLID Principles of Refactoring Presentation - Inland Empire User GroupSOLID Principles of Refactoring Presentation - Inland Empire User Group
SOLID Principles of Refactoring Presentation - Inland Empire User Group
 
Presentation CentOS
Presentation CentOS Presentation CentOS
Presentation CentOS
 
SOLID Principles and Design Patterns
SOLID Principles and Design PatternsSOLID Principles and Design Patterns
SOLID Principles and Design Patterns
 
Install Linux CentOS 7.0
Install Linux CentOS 7.0Install Linux CentOS 7.0
Install Linux CentOS 7.0
 
BDD with JBehave and Selenium
BDD with JBehave and SeleniumBDD with JBehave and Selenium
BDD with JBehave and Selenium
 

Similar to SOLID mit 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 beyond
Mario Fusco
 

Similar to SOLID mit Java 8 (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
 
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
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing JavaJDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Java8
Java8Java8
Java8
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 

Recently uploaded

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
shinachiaurasa2
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
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
VictoriaMetrics
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

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
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton 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
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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
 
%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
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
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...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%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
 

SOLID mit Java 8

  • 1. SOLID mit Java 8 Java Forum Stuttgart 2016
  • 2. Roland Mast Sybit GmbH Agiler Software-Architekt Scrum Master roland.mast@sybit.de
  • 3. Roland Mast Sybit GmbH Agiler Software-Architekt roland.mast@sybit.de
  • 4. 5 Principles • Single responsibility • Open Closed • Liskov Substitution • Interface Segregation • Dependency Inversion SOLID und Uncle Bob
  • 5. Single Responsibility Principle? Single Responsibility Principle? A class should have one, and only one, reason to change. A class should have one, and only one, reason to change.
  • 6. // Strings in einem Array nach deren Länge sortieren Arrays.sort(strings, new Comparator<String>() { public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); } }); Arrays.sort(strings, (a, b) -> Integer.compare(a.length(), b.length())); // Strings alphabetisch sortieren Arrays.sort(strings, String::compareToIgnoreCase); Lambdas
  • 7. List<Person> persons = Arrays.asList( // name, age, size new Person("Max", 18, 1.9), new Person("Peter", 23, 1.8), new Person("Pamela", 23, 1.6), new Person("David", 12, 1.5)); Double averageSize = persons .stream() .filter(p -> p.age >= 18) .collect(Collectors.averagingDouble(p -> p.size)); Lambdas in Streams Iteration über die Daten Filtern anstatt if (age >= 18) { keep(); } Collectors berechnet den Durchschnitt Single Responsibility
  • 8. public interface BinaryOperation { long identity(); long binaryOperator(long a, long b); } public class Sum implements BinaryOperation { @Override public long identity() { return 0L; } @Override public long binaryOperator(long a, long b) { return a + b; } } Single Responsibility private long[] data; public long solve() { int threadCount = Runtime.getRuntime().availableProcessors(); ForkJoinPool pool = new ForkJoinPool(threadCount); pool.invoke(this); return res; } protected void compute() { if (data.length == 1) { res=operation.binaryOperator(operation.identity(), data[0]); } else { int midpoint = data.length / 2; long[] l1 = Arrays.copyOfRange(data, 0, midpoint); long[] l2 = Arrays.copyOfRange(data, midpoint, data.length); SolverJ7 s1 = new SolverJ7(l1, operation); SolverJ7 s2 = new SolverJ7(l2, operation); ForkJoinTask.invokeAll(s1, s2); res = operation.binaryOperator(s1.res, s2.res); } } Daten müssen selbst aufgeteilt und zusammengeführt werden Interface und Klasse definieren Operation Parallele Summenberechnung Threadpool muss selbst erzeugt werden
  • 9. private long[] data; public long sumUp() { return LongStream.of(data) .parallel() .reduce(0, (a, b) -> a + b); } Parallel ReduceSingle Responsibility
  • 10. Single Responsibility Principle Lambdas + Streams Kapseln Verantwortlichkeiten
  • 11. Open/Closed Principle? Open/Closed Principle? You should be able to extend a classes behavior, without modifying it. You should be able to extend a classes behavior, without modifying it.
  • 12. public interface Iterable<T> { Iterator<T> iterator(); } Iterable Interface public interface Iterable<T> { Iterator<T> iterator(); void forEach(Consumer<? super T> action); Spliterator<T> spliterator(); } Open/Closed
  • 13. public interface Iterable<T> { Iterator<T> iterator(); default void forEach(Consumer<? super T> action) { for (T t : this) { action.accept(t); } } default Spliterator<T> spliterator() { return Spliterators.spliteratorUnknownSize(iterator(), 0); } } Default-ImplementationOpen/Closed
  • 14. Open/Closed Principle Default-Implementierungen in Interfaces Flexibel Frameworks erweitern
  • 15. Liskov's Substitution Principle? Liskov's Substitution Principle? “No new exceptions should be thrown by methods of the subtype, except where those exceptions are themselves subtypes of exceptions thrown by the methods of the supertype.” Derived classes must be substitutable for their base classes. Derived classes must be substitutable for their base classes.
  • 16. /** * Find the first occurrence of a text in files * given by a list of file names. */ public Optional<String> findFirst( String text, List<String> fileNames) { return fileNames.stream() .map(name -> Paths.get(name)) .flatMap(path -> Files.lines(path)) .filter(s -> s.contains(text)) .findFirst(); } Checked Exception in StreamsLiskov‘s Substitution public final class Files { public static Stream<String> lines(Path path) throws IOException { BufferedReader br = Files.newBufferedReader(path); try { return br.lines() .onClose(asUncheckedRunnable(br)); } catch (Error|RuntimeException e) { ….. 8< …………………… br.close(); ….. 8< …………………… } } IOException
  • 17. /** * Find the first occurrence of a text in files * given by a list of file names. */ public Optional<String> findFirst( String text, List<String> fileNames) { return fileNames.stream() .map(name -> Paths.get(name)) .flatMap(path -> mylines(path)) .filter(s -> s.contains(text)) .findFirst(); } Handle IOExceptionLiskov‘s Substitution private Stream<String> mylines(Path path){ try (BufferedReader br = Files.newBufferedReader(path)) { return br.lines() .onClose(asUncheckedRunnable(br)); } catch (IOException e) { throw new UncheckedIOException(e); } }
  • 18. private static Runnable asUncheckedRunnable(Closeable c) { return () -> { try { c.close(); } catch (IOException e) { throw new UncheckedIOException(e); } }; } Close StreamLiskov‘s Substitution java.io.BufferedReader::lines + java.nio.file.Files::find, lines, list, walk werfen UncheckedIOException beim Zugriff innerhalb des Streams
  • 19. Liskov´s Substitution Principle Files + BufferedReader UncheckedIOException nur bei neuen Methoden
  • 20. Interface Segregation Principle? Interface Segregation Principle? Make fine grained interfaces that are client specific. Make fine grained interfaces that are client specific.
  • 21. public interface ParserContext { Reader getReader(); void handleLine(String line); void handleException(Exception e); } public void parse(final ParserContext context) { try (BufferedReader br = new BufferedReader(context.getReader())) { String line; do { line = br.readLine(); if (line != null) { context.handleLine(line); } } while (line != null) } catch (IOException e) { context.handleException(e); } } InterfacesInterface Segregation 1 Interface mit 3 Methoden
  • 22. <T> T withLinesOf(Supplier<Reader> reader, Function<Stream<String>, T> handleLines, Function<Exception, RuntimeException> transformException) { try (BufferedReader br = new BufferedReader(reader.get())) { return handleLines.apply(br.lines()); } catch (IOException e) { throw transformException.apply(e); } } Functional InterfacesInterface Segregation 3 separate Interfaces
  • 23. withLinesOf( () -> reader, lines -> lines .filter(line -> line.contains("ERROR")) .map(line -> line.split(":")[1]) .collect(toList()), LogAnalyseException::new); Functional InterfacesInterface Segregation
  • 25. Interface Segregation Principle Functional Interfaces Ermutigen zum Auftrennen von Interfaces
  • 26. Dependency Inversion Principle? Dependency Inversion Principle? Depend on abstractions, not on concretions. Depend on abstractions, not on concretions.
  • 27. Warning: JDK internal APIs are unsupported and private to JDK implementation that are subject to be removed or changed incompatibly and could break your application. Please modify your code to eliminate dependency on any JDK internal APIs. For the most recent update on JDK internal API replacements, please check: https://wiki.openjdk.java.net/display/JDK8/Jav a+Dependency+Analysis+Tool jdeps -jdkinternalsDependency Inversion
  • 28. jdeps -jdkinternals classes classes -> C:Program FilesJavajdk1.8.0_74jrelibrt.jar de.sybit.warranty.facade.impl.DefaultWarrantyFacade (classes) -> com.sun.xml.internal.fastinfoset.stax.events.Util JDK internal API (rt.jar) jdepsDependency Inversion return (Util.isEmptyString(param) || "*".equals(param));
  • 29. public List<String> filterError(Reader reader) { try (BufferedReader br =new BufferedReader(reader)){ return br.lines() .filter(line -> line.contains("ERROR")) .map(line -> line.split(":")[1]) .collect(toList()); } catch (IOException e) { throw new LogAnalyseException(e); } } LambdasDependency Inversion Filterimplementierung ist abhängig von konkreten Implementierungen
  • 30. private Parser parser = new Parser(); public List<String> filterError(Reader reader) { return parser.withLinesOf( reader, lines -> lines .filter(line -> line.contains("ERROR")) .map(line -> line.split(":")[1]) .collect(toList()), LogAnalyseException::new); } LambdasDependency Inversion filterError() ist nur noch abhängig von Abstraktionen
  • 31. public class Parser { <T> T withLinesOf(Reader reader, Function<Stream<String>, T> handleLines, Function<Exception, RuntimeException> onError) { try (BufferedReader br = new BufferedReader(reader)) { return handleLines.apply(br.lines()); } catch (IOException e) { throw onError.apply(e); } } } LambdasDependency Inversion withLinesOf() kapselt die Abhängigkeiten
  • 33. module MyClient { requires MyService; } module MyService { exports de.sybit.myservice; } SOLID mit Java 9 - Jigsaw
  • 34. “The principles of software design still apply, regardless of your programming style. The fact that you've decided to use a [functional] language that doesn't have an assignment operator does not mean that you can ignore the Single Responsibility Principle; or that the Open Closed Principle is somehow automatic.” Robert C. Martin: OO vs FP (24 November 2014) http://blog.cleancoder.com/uncle-bob/2014/11/24/FPvsOO.html SOLID mit Java – OO vs FP
  • 35. Roland Mast, Sybit GmbH Agiler Software-Architekt roland.mast@sybit.de