Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functional principles for object-oriented

Similar presentations


Presentation on theme: "Functional principles for object-oriented"— Presentation transcript:

1 functional principles for object-oriented development @jessitron

2

3

4 Imperative Procedural Object-Oriented Functional Aspect-Oriented Logic

5

6

7 Data In, Data Out Immutability Verbs Are People Too Declarative Style Specific Typing Lazy Evaluation

8 What is it? Principle What is it? We already do it What’s the point? What is it? Scala / F# Java / C#

9 Data In, Data Out

10 access global state modify input change the world

11 Data In -> ? -> Data out input output

12 Testable Easier to understand

13 the flow of data

14

15 List List > List

16 Problem easier, because we know each step of the way of data.

17 public string CreateAccount(UserDbService db, String email, String password) { … }

18 String password; String email; private boolean invalidPassword() { return !password.contains(email); }

19 private boolean invalidPassword(String password, String email) { return !password.contains(email); }

20 Immutability

21 modify anything

22 Concurrency fewer possibilities

23 NPE

24 c c

25 String Effective Java Effective C#

26 Scala val qty = 4 // immutable var n = 2 // mutable

27 let qty = 4 // immutable let mutable n = 2 // mutable n = 4 // false n <- 4 // destructive update F#

28 C#: easy public struct Address { private readonly string city; public Address(string city) : this() { this.city = city; } public string City { get { return city; } }

29 Java: defensive copy private final ImmutableList phones; public Customer (Iterable phones) { this.phones = ImmutableList.copyOf(phones); }

30 Java: copy on mod public Customer addPhone(Phone newPhone) { Iterable morePhones = ImmutableList.builder().addAll(phones).add(newPhone).build(); return new Customer(morePhones); }

31 fruit fruit.add(tomato)

32 F#: copy on mod member this.AddPhone (newPhone : Phone) { new Customer(newPhone :: phones) }

33 C#: shallow copy public Customer AddPhone(Phone newPhone) { IEnumerable morePhones = // create list return new Customer(morePhones, name, address, birthday, cousins); }

34 this talk is brought to you by… the Option type! NPE Thing doStuff() NullThing doStuff() {} SomeThing doStuff() {…} Option None Some

35 … because null is not a valid object reference. Optional FSharpOption

36 Verbs Are People Too

37

38 Imperative Procedural Object-Oriented Functional Aspect-Oriented Logic !=

39 Strategy Command OnClick() release ( )

40 class CostInflation implements FunctionOverTime { public float valueAt(int t) { return // some calculated value; } Java

41 val costInflation = Variable ( “Cost Inflation”, t => Math.pow(1.15,t)) val seasonalVolume = Array(0.95,0.99,1.01,…) val seasonalAdjustment = Variable(“Season”, t => seasonalVolume(t)) Scala

42 C# private readonly Func calc; public Func ValueAt { get { return calc; } }

43 C# var inflation = new Variable(“Inflation”, t => Math.Pow(1.15,t)); inflation.ValueAt(3);

44 Java Variable inflation = new Variable (“Inflation”, new Function () { @Override public Double apply(Integer input) { return Math.pow(1.15, input); } });

45 Java 8 Variable inflation = new Variable (“Inflation”, t => Math.pow(1.15, t) );

46 Declarative Style

47 say what you’re doing, not how you’re doing it

48 Select ROLE_NAME, UPDATE_DATE From USER_ROLES Where USER_ID = :userId

49 smaller pieces readable code

50 familiar != readable

51 Java public List findBugReports(List lines) { List output = new LinkedList(); for(String s : lines) { if(s.startsWith(“BUG”)) { output.add(s); } return output; }

52 Scala lines.filter( _.startsWith(“BUG”)) lines.par.filter( _.startsWith(“BUG”))

53 Java final Predicate startsWithBug = new Predicate () { public boolean apply(String s) { return s.startsWith("BUG"); } }; filter(list, startsWithBug);

54 C# lines.Where(s => s.StartsWith(“BUG”)).ToList

55 this talk is brought to you by… the Tuple type! function new Tuple (“You win!”, 1000000)

56 When one return value is not enough! Tuple

57 Specific Typing

58 expressiveness catch errors early

59

60

61 The beginning of wisdom is to call things by their right names.

62 F# [ ] type cents let price = 599

63 Scala type FirstName = String // type alias Customer(name : FirstName, home : EmailAddress)

64 Scala case class FirstName(value : String) let friend = FirstName(“Ivana”);

65 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() {...} }

66 State everything you need State only what you need

67 Scala List [+A] def indexOf [B >: A] (elem: B): IntInt def sameElements (that: GenIterable[A]): BooleanIterable[A]

68 C#: weak public boolean Valid(Customer cust) { EmailAddress email = cust.EmailAddress; // exercise business logic return true; }

69 C#: weak public boolean Valid(IHasEmailAddress anything) { EmailAddress email = anything.EmailAddress; // exercise business logic return true; } interface IHasEmailAddress { string EmailAddress {get; } }

70 Lazy Evaluation

71 delay evaluation until the last responsible moment

72 save work separate “what to do” from “when to stop”

73 int bugCount = 0; String nextLine = file.readLine(); while (bugCount < 40) { if (nextLine.startsWith("BUG")) { String[] words = nextLine.split(" "); report("Saw "+words[0]+" on "+words[1]); bugCount++; } waitUntilFileHasMoreData(file); nextLine = file.readLine(); } Java

74 for (String s : FluentIterable.of(new RandomFileIterable(br)).filter(STARTS_WITH_BUG_PREDICATE).transform(TRANSFORM_BUG_FUNCTION).limit(40).asImmutableList()) { report(s); } Java Iterable: laziness is a virtue

75 C# IEnumerable ReadLines(StreamReader r) { while (true) { WaitUntilFileHasMoreData(r); yield return r.ReadLine(); }

76 Data In, Data Out Immutability Verbs Are People Too Declarative Style Specific Typing Lazy Evaluation

77 I promise not to exclude from consideration any idea based on its source, but to consider ideas across schools and heritages in order to find the ones that best suit the current situation.

78

79

80 Man, the living creature, the creating individual, is always more important than any established style or system. – Bruce Lee @jessitron Jessica Kerr blog.jessitron.com github.com/jessitron/fp4ood


Download ppt "Functional principles for object-oriented"

Similar presentations


Ads by Google