Goals for today
1) Look at functional principles
2) Learn how functional programmers
solve problems
3) Solve more problems
Slide 8
Slide 8 text
Immutability
Verbs Are People Too
Declarative Style
Null Is Your Enemy
Strong Typing
Lazy Evaluation
Slide 9
Slide 9 text
Principle
What is it?
We already do it
What’s the point?
Functional
Java
Slide 10
Slide 10 text
Immutability
Slide 11
Slide 11 text
What is it?
The value of an identifier never
changes.
Objects never change state.
Slide 12
Slide 12 text
We already do it
• java.lang.String
• Effective Java
Slide 13
Slide 13 text
What’s the point?
• The less state that can change, the
less you have to think about.
• Concurrency!
Slide 14
Slide 14 text
Immutability in functional
languages
Pure: everything is immutable.
Hybrid: immutable by default
Slide 15
Slide 15 text
Immutability in functional
languages
fruit
tomato :: fruit
Slide 16
Slide 16 text
Immutability in Java
final
Slide 17
Slide 17 text
Immutability in Java
ImmutableMap.copyOf(mutableMap)
ImmutableList.of(item,
item, item)
Slide 18
Slide 18 text
Immutability in Java
Keep it simple.
Slide 19
Slide 19 text
Verbs are people too
Slide 20
Slide 20 text
What is it?
Functions are values. They can be
passed around just like data.
Slide 21
Slide 21 text
We already do it
• Strategy pattern
• Command pattern
How
What
Slide 22
Slide 22 text
We already do it
onClick
release ( )
Slide 23
Slide 23 text
What’s the point?
Passing around instructions is useful.
Slide 24
Slide 24 text
Verbs in functional
languages
case class User(val firstName : String)
val sortedList = userList.sortBy(u -> u.firstName)
def getFirstName (u : User) = u.firstName
Slide 25
Slide 25 text
Verbs in Java
Collections.sort(myUserList,
new Comparator() {
public int compare(User o1, User o2) {
return
o1.firstName.compareTo(o2.firstName);
}
};
);
Iterables.transform(bugLines,
reformatBugLine)
Slide 26
Slide 26 text
Verbs in Java
getFirstName = new Function() {
public String apply(User user) {
return user.firstName;
}
};
Ordering o = Ordering.natural().onResultOf(getFirstName);
List sortedList = o.sortedCopy(userList);
Iterables.transform(bugLines,
reformatBugLine)
What is it?
Say what you’re doing, not how you’re
doing it.
Slide 30
Slide 30 text
We already do it
• Refactoring: single-line method
Slide 31
Slide 31 text
We already do it
Select USER_NAME, count(*),
max(update_date)
From USER_ROLES
Where USER_ID = :userId
Group by USER_NAME
Slide 32
Slide 32 text
What’s the point?
Readable code
Smaller, simpler pieces
Slide 33
Slide 33 text
Declarative style in
functional languages
• Many small functions
• One-line collection processing
linesFromFile.filter ( _.startsWith(“BUG”))
Slide 34
Slide 34 text
Declarative style in Java?
for (String line : list) {
if (line.startsWith("BUG")) {
report(line);
}
}
Slide 35
Slide 35 text
Declarative style in Java
reportAll(filterForBugs(list));
Slide 36
Slide 36 text
List bugLines = new LinkedList();
for (String line : list) {
if (line.startsWith("BUG")) {
bugLines.add(line);
}
}
return bugLines;
Declarative style in Java?
Slide 37
Slide 37 text
final Predicate startsWithBug =
new Predicate() {
public boolean apply(String s) {
return s.startsWith("BUG");
}
};
Iterable bugLines = filter(list, startsWithBug);
Declarative style in Java
Slide 38
Slide 38 text
Null Is Your Enemy
Slide 39
Slide 39 text
What is it?
A null reference is not a valid object
reference. Let’s stop treating it like
one.
Slide 40
Slide 40 text
We already do it
Thingiebob
doStuff()
NullThingiebob
doStuff() {}
SomeThingiebob
doStuff() {…}
Slide 41
Slide 41 text
What’s the point?
Slide 42
Slide 42 text
Defeating null in
functional languages
Option
None
Some
Slide 43
Slide 43 text
Defeating null in Java
if (banana.isPresent()) {
String contents = banana.get();
}
Optional banana = Optional.of("banana");
Optional noBanana = Optional.absent();
Slide 44
Slide 44 text
Defeating null in Java
Optional.fromNullable(mightBeNull);
Slide 45
Slide 45 text
Strong typing
Slide 46
Slide 46 text
What is it?
When the wrong type of data is passed
in, the compiler complains.
Slide 47
Slide 47 text
We already do it
Java is strongly typed, right?
Slide 48
Slide 48 text
We already do it
Slide 49
Slide 49 text
What’s the point?
The beginning of wisdom is to call things by their right
names.
Slide 50
Slide 50 text
What’s the point?
% of errors found
at compile-time
Typing
Strong Weak
This data
is
completely
made up.
Slide 51
Slide 51 text
Strong typing in
functional languages
type FirstName = String // Haskell type alias
data User = User FirstName EmailAddress
// Haskell data type
Slide 52
Slide 52 text
Strong typing in
functional languages
List [+A] // from Scaladoc
def indexOf [B >: A] (elem: B): Int
def
sameElements (that: GenIterable[A]): Boolean
Slide 53
Slide 53 text
Strong typing in Java
public User(FirstName name, EmailAddress login)
public class FirstName {
public final String stringValue;
public FirstName(final String
value) {
this.stringValue = value;
}
public String toString() {...}
public boolean equals() {...}
public int hashCode() {...}
}
Slide 54
Slide 54 text
new User(firstName(“Joe”),
emailAddress(“[email protected]”));
public static FirstName firstName(String value)
{
return new FirstName(value);
}
Strong typing in Java
Slide 55
Slide 55 text
public boolean validateUser(User user)
{
EmailAddress email = user.getEmailAddress();
// exercise business logic
return true;
}
Strong typing in Java
Slide 56
Slide 56 text
public boolean validate(HasEmailAddress anything)
{
EmailAddress email = anything.getEmailAddress();
// exercise business logic
return true;
} interface HasEmailAddress {
EmailAddress getEmailAddress();
}
Strong typing in Java
Slide 57
Slide 57 text
Lazy evaluation
Slide 58
Slide 58 text
What is it?
Delaying evaluation of an expression
until the last responsible moment.
Slide 59
Slide 59 text
We already do it
Providers, Factories
SQL Cursors
Slide 60
Slide 60 text
What’s the point?
You may never even need it.
Separate “what to do” from
“when to stop.”
Slide 61
Slide 61 text
Lazy evaluation in
functional languages
• Haskell is lazy by default
• F# provides a Lazy<_> type
• Infinite sequences
Slide 62
Slide 62 text
Lazy evaluation in Java
Callable
Iterable
Slide 63
Slide 63 text
int bugCount = 0;
String nextLine = file.readLine();
while (bugCount < 40) {
if (nextLine.startsWith("BUG")) {
String[] words = nextLine.split(" ");
report("Saw the bug at "+words[0]+" on "+ words[1]);
bugCount++;
}
waitUntilFileHasMoreData(file);
nextLine = file.readLine();
}
Imperative Java
Slide 64
Slide 64 text
for (String s : take(new RandomFileIterable(br))
.filterBy(STARTS_WITH_BUG_PREDICATE)
.transformWith(TRANSFORM_BUG_FUNCTION)
.limit(40)
.asImmutableList()) {
report(s);
}
Functional style
Slide 65
Slide 65 text
Immutability
Verbs Are People Too
Declarative Style
Null Is Your Enemy
Strong Typing
Lazy Evaluation
Slide 66
Slide 66 text
Thank you
Jessica Kerr @jessitron
Jessitron.blogspot.com
[email protected]
http://speakerdeck.com/u/jessitron/
Look for me at KCDC
April 27-28 2012: kcdc.info