SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
Java design patterns in
Scala
Radim Pavlicek
About me
● Java/Scala developer
● bogey golfer
● piano player
Agenda
Part I - OO Patterns
Functional Interface
Command
Builder
Iterator
Template method
Strategy
Null Object
Functional Interface
encapsulate a bit of program logic and treated
like any other first-class construct
Java
Collections.sort(people,
new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getFirstName().compareTo(
ps.getFirstName())
}
})
Java
other use-cases
● runnable
● callable
Java 8 has solved
Scala
people.sortWith(
(p1, p2) => p1.firstName < p2.firstName
)
Command
Turn a method invocation into an object
and execute it in a central location
Java
public class PrintCommand implements Runnable {
private final String s;
PrintCommand(String s) { this.s = s; }
public void run() { System.out.println(s); }
}
public class Invoker {
private final List<Runnable> history = new ArrayList<>();
void invoke(Runnable command) {
command.run();
history.add(command);
}
}
Invoker invoker = new Invoker();
invoker.invoke( new PrintCommand( "Scala"));
invoker.invoke( new PrintCommand( "Vienna"));
Scala
object Invoker {
private var history: Seq[() => Unit] = Seq.empty
def invoke(command: => Unit) { // by-name parameter
command
history :+= command _
}
}
Invoker.invoke(println( "foo"))
Scala advanced
def makePurchase(register: CaschRegister, amount: Int) =
{
() = {
println("Purchase in amount: " + amount)
register.addCash(amount)
}
}
// how to create purchase functions using closure
Builder
to create an immutable object using a friendly
syntax
Java
Issues
● constructor arguments
Person(String n,String n2,String nick
● Defaults (telescoping constructor problem)
Person()
Person(String name)
Person(String name, String name2)...
Java code
public class ImmutablePerson {
private final String firstName;
public String getFirstName() {
return firstName;}
private ImmetablePerson(Builder builder) {
firstName = builder.firstName;
}
public static Builder newBuilder() {
return new Builder();
}
}
public static class Builder {
private String firstName;
public Builder withFirstName(String
firstName) {
this.firstName = firstName;
return this;
}
public ImmutablePerson build () {
return new ImmutablePerson(this);
}
}
Scala - Case Class
case class Person {
firstName: String,
LastName: String,
nick: String = "")
val p = Person(firstName = “Radim”, lastName = “Pavlicek”)
val cloneMe = Person(firstName = “Radim”, lastName = “Pavlicek”)
p.equals(cloneMe) // true
val brother = p.copy(firstName = “Libor”) // Libor Pavlicek
p.toString // Person[firstName=”Radim”, lastName= “Pavlicek”]
Scala - Tuples
● for explorative development
def p = (“Radim”, “Pavlicek”)
p._1 // Radim
p._2 // Pavlicek
Iterator
iterate through the elements of a sequence
without having to index into it
Java
public Set<Char> vowelsCount(String s) {
Set<Char> l = new HashSet<Char>();
for (Char c : s.toLowerCase().toCharArray())
if (isVowel(c))
l.add(c)
}
Scala
● filter
● map
● reduce
Scala filter
filtering certain elements from collection
def vowelsNumber(word : String) =
word.filter(isVowel).toSet
vowelsNumber(“Radim”) // Set(‘a’, ‘i’)
Scala map
function is applied to each element
def prependHello(names : Seq[String]) =
names.map((name) => “Hello, “ + name)
Scala reduce
reduce sequence to a single value
def sum(sq : Seq[Int]) =
if (sq.isEmpty) 0
else
sq.reduce((acc,curr) => acc + curr)
Scala comprehensions
● guard
for (a <- list if isEven(a))
● pattern matching
for (Person(name, address) <- people)
● still no mutable state
Scala for comprehensions
case class Person(name: String, addr: Address)
case class Address(zip: Int)
def greetings(people: Seq[Person]) =
for (Person(name, address) <-
people if isCloseZip(address.zip) )
yield “Hello, %s”.format(name)
Template method
defines the program skeleton of an algorithm in
a method, called template method, which defers
some steps to subclasses
Java
public abstract class Template {
public void doStuff() {
beforeStuff(); afterStuff();
}
protected abstract void beforeStuff();
protected abstract void afterStuff();
}
Scala Function Builder
def doStuff(
beforeStuff: () => Unit,
afterStuff: () => Unit) =
() = {
beforeSuff()
afterStuff()
}
Scala Function Builder
def beforeStuff() = Console.println(“before”)
def afterStuff() = Console.println(“after”)
val test= doStuff(beforeStuff, afterStuff)
scala> test
Strategy
define an algorithm in abstract terms and make
it interchangeable within family
Java
public interface Strategy {
int compute(int a, int b);
}
public class Add implements Strategy {
public int compute(int a, int b) { return a + b; }
}
public class Multiply implements Strategy {
public int compute(int a, int b) { return a * b; }
}
public class Context {
private final Strategy strategy;
public Context(Strategy strategy) { this.strategy = strategy; }
public void use(int a, int b) { strategy.compute(a, b); }
}
new Context(new Multiply()).use(2, 3);
Scala
define type alias and use first-class functions
type Strategy = (Int, Int) => Int
class Context(computer: Strategy) {
def use(a: Int, b: Int) { computer(a, b) }
}
val add: Strategy = _ + _
val multiply: Strategy = _ * _
new Context(multiply).use( 2, 3)
Null Object
avoid null checks in code and
centralize logic that deals with handling the
absence of a value
Java
class NullPerson extends Person {....}
public Person build(String first, String last) {
if (first == null || last == null)
return new NullPerson();
return new Person (first, last);
}
Scala
val nullPerson = Person() // case class
def build(first: Option[String],
last: Option[String]) =
(for (f <- first; l <- last)
yield Person(f, l)
).getOrElse(nullPerson)
Decorator
add behaviour to an existing class
aka “there is a bug in the API class”
Java
public interface OutputStream {
void write(byte b);
void write(byte[] b);
}
public class FileOutputStream implements OutputStream { /* ... */ }
public abstract class OutputStreamDecorator implements OutputStream {
protected final OutputStream delegate;
protected OutputStreamDecorator(OutputStream delegate) {
this.delegate = delegate;
}
public void write(byte b) { delegate.write(b); }
public void write(byte[] b) { delegate.write(b); }
}
Scala
def add(a: Int, b: Int) = a + b
def decorateLogger(calcF: (Int, Int) => Int) =
(a: Int, b: Int) => {
val result = calcF(a, b)
println(“Result is: “ + result) // here it comes
result
}
Scala
val loggingAdd = decorateLogger(add)
scala> loggingAdd(1,4)
Result is 5
Sources
http://pavelfatin.com/design-patterns-in-scala

Contenu connexe

Tendances

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentMaty Fedak
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about LambdasRyan Knight
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developersjessitron
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako, Vasil Remeniuk
 
GUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingGUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingDavid Muñoz Díaz
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
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
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerDavid Muñoz Díaz
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 

Tendances (20)

Templates
TemplatesTemplates
Templates
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and Reagent
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developers
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
GUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingGUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programming
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 

Similaire à Java patterns in Scala

Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvmIsaias Barroso
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basicswpgreenway
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to ScalaRiccardo Cardin
 
Real world scala
Real world scalaReal world scala
Real world scalalunfu zhong
 

Similaire à Java patterns in Scala (20)

Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala
ScalaScala
Scala
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Real world scala
Real world scalaReal world scala
Real world scala
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 

Dernier

Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%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
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
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
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%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
 
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
 
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...SelfMade bd
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
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
 
%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
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
%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
 
%+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
 

Dernier (20)

Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%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
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
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
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
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
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%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
 
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...
 
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 new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
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 ...
 
%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
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%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
 
%+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...
 

Java patterns in Scala

  • 1. Java design patterns in Scala Radim Pavlicek
  • 2. About me ● Java/Scala developer ● bogey golfer ● piano player
  • 4. Part I - OO Patterns Functional Interface Command Builder Iterator Template method Strategy Null Object
  • 5. Functional Interface encapsulate a bit of program logic and treated like any other first-class construct
  • 6. Java Collections.sort(people, new Comparator<Person>() { public int compare(Person p1, Person p2) { return p1.getFirstName().compareTo( ps.getFirstName()) } })
  • 7. Java other use-cases ● runnable ● callable Java 8 has solved
  • 8. Scala people.sortWith( (p1, p2) => p1.firstName < p2.firstName )
  • 9. Command Turn a method invocation into an object and execute it in a central location
  • 10. Java public class PrintCommand implements Runnable { private final String s; PrintCommand(String s) { this.s = s; } public void run() { System.out.println(s); } } public class Invoker { private final List<Runnable> history = new ArrayList<>(); void invoke(Runnable command) { command.run(); history.add(command); } } Invoker invoker = new Invoker(); invoker.invoke( new PrintCommand( "Scala")); invoker.invoke( new PrintCommand( "Vienna"));
  • 11. Scala object Invoker { private var history: Seq[() => Unit] = Seq.empty def invoke(command: => Unit) { // by-name parameter command history :+= command _ } } Invoker.invoke(println( "foo"))
  • 12. Scala advanced def makePurchase(register: CaschRegister, amount: Int) = { () = { println("Purchase in amount: " + amount) register.addCash(amount) } } // how to create purchase functions using closure
  • 13. Builder to create an immutable object using a friendly syntax
  • 14. Java Issues ● constructor arguments Person(String n,String n2,String nick ● Defaults (telescoping constructor problem) Person() Person(String name) Person(String name, String name2)...
  • 15. Java code public class ImmutablePerson { private final String firstName; public String getFirstName() { return firstName;} private ImmetablePerson(Builder builder) { firstName = builder.firstName; } public static Builder newBuilder() { return new Builder(); } } public static class Builder { private String firstName; public Builder withFirstName(String firstName) { this.firstName = firstName; return this; } public ImmutablePerson build () { return new ImmutablePerson(this); } }
  • 16. Scala - Case Class case class Person { firstName: String, LastName: String, nick: String = "") val p = Person(firstName = “Radim”, lastName = “Pavlicek”) val cloneMe = Person(firstName = “Radim”, lastName = “Pavlicek”) p.equals(cloneMe) // true val brother = p.copy(firstName = “Libor”) // Libor Pavlicek p.toString // Person[firstName=”Radim”, lastName= “Pavlicek”]
  • 17. Scala - Tuples ● for explorative development def p = (“Radim”, “Pavlicek”) p._1 // Radim p._2 // Pavlicek
  • 18. Iterator iterate through the elements of a sequence without having to index into it
  • 19. Java public Set<Char> vowelsCount(String s) { Set<Char> l = new HashSet<Char>(); for (Char c : s.toLowerCase().toCharArray()) if (isVowel(c)) l.add(c) }
  • 21. Scala filter filtering certain elements from collection def vowelsNumber(word : String) = word.filter(isVowel).toSet vowelsNumber(“Radim”) // Set(‘a’, ‘i’)
  • 22. Scala map function is applied to each element def prependHello(names : Seq[String]) = names.map((name) => “Hello, “ + name)
  • 23. Scala reduce reduce sequence to a single value def sum(sq : Seq[Int]) = if (sq.isEmpty) 0 else sq.reduce((acc,curr) => acc + curr)
  • 24. Scala comprehensions ● guard for (a <- list if isEven(a)) ● pattern matching for (Person(name, address) <- people) ● still no mutable state
  • 25. Scala for comprehensions case class Person(name: String, addr: Address) case class Address(zip: Int) def greetings(people: Seq[Person]) = for (Person(name, address) <- people if isCloseZip(address.zip) ) yield “Hello, %s”.format(name)
  • 26. Template method defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses
  • 27. Java public abstract class Template { public void doStuff() { beforeStuff(); afterStuff(); } protected abstract void beforeStuff(); protected abstract void afterStuff(); }
  • 28. Scala Function Builder def doStuff( beforeStuff: () => Unit, afterStuff: () => Unit) = () = { beforeSuff() afterStuff() }
  • 29. Scala Function Builder def beforeStuff() = Console.println(“before”) def afterStuff() = Console.println(“after”) val test= doStuff(beforeStuff, afterStuff) scala> test
  • 30. Strategy define an algorithm in abstract terms and make it interchangeable within family
  • 31. Java public interface Strategy { int compute(int a, int b); } public class Add implements Strategy { public int compute(int a, int b) { return a + b; } } public class Multiply implements Strategy { public int compute(int a, int b) { return a * b; } } public class Context { private final Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void use(int a, int b) { strategy.compute(a, b); } } new Context(new Multiply()).use(2, 3);
  • 32. Scala define type alias and use first-class functions type Strategy = (Int, Int) => Int class Context(computer: Strategy) { def use(a: Int, b: Int) { computer(a, b) } } val add: Strategy = _ + _ val multiply: Strategy = _ * _ new Context(multiply).use( 2, 3)
  • 33. Null Object avoid null checks in code and centralize logic that deals with handling the absence of a value
  • 34. Java class NullPerson extends Person {....} public Person build(String first, String last) { if (first == null || last == null) return new NullPerson(); return new Person (first, last); }
  • 35. Scala val nullPerson = Person() // case class def build(first: Option[String], last: Option[String]) = (for (f <- first; l <- last) yield Person(f, l) ).getOrElse(nullPerson)
  • 36. Decorator add behaviour to an existing class aka “there is a bug in the API class”
  • 37. Java public interface OutputStream { void write(byte b); void write(byte[] b); } public class FileOutputStream implements OutputStream { /* ... */ } public abstract class OutputStreamDecorator implements OutputStream { protected final OutputStream delegate; protected OutputStreamDecorator(OutputStream delegate) { this.delegate = delegate; } public void write(byte b) { delegate.write(b); } public void write(byte[] b) { delegate.write(b); } }
  • 38. Scala def add(a: Int, b: Int) = a + b def decorateLogger(calcF: (Int, Int) => Int) = (a: Int, b: Int) => { val result = calcF(a, b) println(“Result is: “ + result) // here it comes result }
  • 39. Scala val loggingAdd = decorateLogger(add) scala> loggingAdd(1,4) Result is 5