SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and AnnotationsRoshan Deniyage
 
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_keywordsmanish kumar
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java GenericsYann-Gaël Guéhéneuc
 
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 PitfallsRakesh Waghela
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughMahfuz Islam Bhuiyan
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Java8 - Interfaces, evolved
Java8 - Interfaces, evolvedJava8 - Interfaces, evolved
Java8 - Interfaces, evolvedCharles Casadei
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid DeconstructionKevlin Henney
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 InheritanceOUM SAOKOSAL
 
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, JVMmanish kumar
 
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 JVMMario Fusco
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 

Was ist angesagt? (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
 

Andere mochten auch

SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in JavaIonut Bilica
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class designNeetu Mishra
 
Robert martin
Robert martinRobert martin
Robert martinShiraz316
 
Java Code Quality Tools
Java Code Quality ToolsJava Code Quality Tools
Java Code Quality ToolsAnju ML
 
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 GroupAdnan Masood
 
Presentation CentOS
Presentation CentOS Presentation CentOS
Presentation CentOS rommel gavia
 
SOLID Principles and Design Patterns
SOLID Principles and Design PatternsSOLID Principles and Design Patterns
SOLID Principles and Design PatternsGanesh Samarthyam
 
BDD with JBehave and Selenium
BDD with JBehave and SeleniumBDD with JBehave and Selenium
BDD with JBehave and SeleniumNikolay Vasilev
 

Andere mochten auch (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
 

Ähnlich wie SOLID mit Java 8

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 InterfacesRaffi Khatchadourian
 
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...Raffi Khatchadourian
 
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 8Raffi Khatchadourian
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New featuresSon Nguyen
 
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
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
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 JavaSimon Ritter
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
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 CodeIan Robertson
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalUrs Peter
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Kürzlich hochgeladen (20)

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

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