Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×

10 Sets of Best Practices for Java 8

Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Cargando en…3
×

Eche un vistazo a continuación

1 de 85 Anuncio
Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

Similares a 10 Sets of Best Practices for Java 8 (20)

Anuncio

Más de Garth Gilmour (20)

Más reciente (20)

Anuncio

10 Sets of Best Practices for Java 8

  1. 1. Katsconf – September 2016 garth.gilmour@instil.co Put the Lime in the Coconut • 10 Best Practices for Java 8 • 10 Sets of Best Practices for Java 8
  2. 2. About this talk…
  3. 3. I’ll Be Your Corporate Shill Today…
  4. 4. How Many Of You Are Using Java 8?
  5. 5. On With The Show!!!
  6. 6. 1. General points about adopting Java 8 2. Using Lambdas and Method Refs 3. Coping with Functional Interfaces 4. Adding ‘Optional<T>’ into your codebase 5. The Streams API and Collections 6. Using Streams outside of collections 7. Functional programming with strings 8. Adding parallelism to streams 9. Simplifying Design Patterns with FP 10. The remainder of Java 8 Sets of Best Practises
  7. 7. Levels of Discussion • High level principles • Designing API’s • Design in general • Low level coding • Pet peeves 
  8. 8. Its Been Amongst Us For Some Time…
  9. 9. Best Practises for Management • You can’t avoid Java 8 • So plan for the pain of change… • The future is (kinda) functional • Your developers may already be eager to embrace it  • Explore other JVM languages • Exploring != adopting • Don’t accidentally encourage use of anti-patterns in Java 8
  10. 10. * Or Clojure, Kotlin, Ceylon etc…
  11. 11. Lambdas and Method References
  12. 12. Replacing Anonymous Inner Classes
  13. 13. Expression Vs. Block Lambdas
  14. 14. Expression Vs. Block Lambdas
  15. 15. Expression Lambdas Good, Block Lambdas Evil…
  16. 16. Best Practises for Lambdas and Method Refs • obj::foo not x -> obj.foo(x) • Only write lambdas which have ‘obviously no errors’ • When in doubt prefer method references to lambdas • Don’t use block lambdas • Eliminate superfluous syntax • Including final on variables which are ‘effectively final’
  17. 17. Functional Interfaces
  18. 18. Know Your Functional Interfaces
  19. 19. Overloading and Functional Interfaces
  20. 20. JavaDoc Guidelines for Functional Interfaces
  21. 21. Best Practises for Functional Interfaces • Learn the functional interfaces • Consider rewriting abstract classes as functional interfaces • Avoid overloading with related functional interfaces • Only write your own functional interfaces when unavoidable • Follow the naming guidelines when you write your own • Use @FunctionalInterface
  22. 22. Optional
  23. 23. The Basics of Optional
  24. 24. The Basics of Optional
  25. 25. • optional.ifPresentOrElse(this::foo, this::bar) • Optional<Account> opt = homeAcct(id).or(() -> workAcct(id)) • List<Email> emails = staff.stream() .map(e -> e.getAddress()) .flatMap(Optional::stream) .collect(toList()) New Optional Features in Java 9 //may not exist
  26. 26. Best Practises for Option • Never return null from a method in your public API • Return an Option instead • Consider whether to require Option within your codebase • Consider if Option as a parameter is useful to you • Never return null from a method that declares Option Be conservative in what you send, be liberal in what you accept Robustness Principle / Postel's Law
  27. 27. Feel the Evil…
  28. 28. Streams and Collections
  29. 29. Basic Use Of Streams
  30. 30. Basic Use Of Streams
  31. 31. Basic Use Of Streams
  32. 32. Basic Use Of Streams
  33. 33. Two Ways to Find the Average NB I do know about ‘IntStream.average’ and ‘Collectors.averagingInt’ etc…
  34. 34. Don’t Go Fully Functional in Java
  35. 35. Best Practises for Streams and Collections Pt1 • Be judicious in your use of the ‘functional toolkit’ • The methods of the toolkit are patterns of iteration • Not every use of iteration cleanly fits the pattern • Don’t obsess about local state • Its global state that’s bad
  36. 36. Why Are Streams Read-Once?
  37. 37. • Streams are typically explained like UNIX pipes • Each call creates a temporary result which is passed on • The reality is somewhat different • A stream pipeline is made up of a source, zero or more intermediate operations and a terminal operation • The terminal operations typically: • Produce an aggregate value (e.g. reduce and collect) • Select a particular item (e.g. findAny and findFirst) • Iterate over the items (forEach) • The operations you specify produce a stream description • This description is executed at the terminal operation • Each stage of the pipeline has a set of flags • These can be used to take shortcuts Understand How Streams Work Internally
  38. 38. The ‘Spliterator’ Interface
  39. 39. The ‘Spliterator’ Interface
  40. 40. Best Practises for Streams and Collections Pt2 • Its good to return streams from the methods of your API • Items can be fetched lazily • The ‘toolkit’ is right there • Regular collections are easy to build from streams • But not in every case • Typically when the data source might change
  41. 41. Using Collectors
  42. 42. Best Practises for Streams and Collections Pt3 • Understand how streams (may) work ‘under the hood’ • Fetching may be lazy • Actions will be postponed till the termination • Shorts-cuts can be taken • Write code in ‘sympathy’ • In particular become familiar with Collectors
  43. 43. Streams and Boxing
  44. 44. Streams and Boxing
  45. 45. Streams and Boxing Without: 1066 With: 2041 Difference: 975 Without: 833 With: 1328 Difference: 495 Without: 833 With: 1330 Difference: 497 Without: 851 With: 1291 Difference: 440 Without: 830 With: 1322 Difference: 492 Without: 862 With: 1365 Difference: 503 Without: 874 With: 1249 Difference: 375 Without: 840 With: 1259 Difference: 419 … Without: 851 With: 1239 Difference: 388 Without: 830 With: 1253 Difference: 423 Without: 843 With: 1231 Difference: 388 Without: 825 With: 1232 Difference: 407 Without: 835 With: 1260 Difference: 425 Without: 837 With: 1244 Difference: 407 Without: 841 With: 1244 Difference: 403 Average difference is: 419.96
  46. 46. Then I Showed This To David…
  47. 47. Streams and Boxing
  48. 48. Streams and Boxing
  49. 49. Streams and Boxing
  50. 50. Streams and Boxing NB: Units are operations per second so bigger is better 
  51. 51. Best Practises for Streams and Collections Pt4 • Be aware of the overhead of boxing when using types such as ‘Stream<Double>’ • Use the specialized types like ‘DoubleStream’ instead
  52. 52. Functional Programming With Strings
  53. 53. Examples of FP With Strings in Other Languages class Program { static void Main(string[] args) { string input = " abc-def#ghi+jkl "; string output = RemovePunctuation(input); Console.WriteLine(output); } private static string RemovePunctuation(string input) { var letters = from c in input.ToLower() where c >= 'a' && c <= 'z' select c; return new string(letters.ToArray()); } } abcdefghijkl
  54. 54. Manipulating Strings Using the Streams API
  55. 55. ‘String.chars’ returns an ‘IntStream’
  56. 56. Best Practises for Strings • Avoid combining the Streams API with String objects
  57. 57. Streams Outside Collections
  58. 58. Using Streams with Zip Files
  59. 59. Using Streams with Zip Files
  60. 60. Using Streams with ‘BufferedReader’
  61. 61. Using Streams with ‘BufferedReader’
  62. 62. Best Practises for Streams and Types • Remember streams are for more than collections • Keep an eye as JSE libraries and open source projects incrementally add support • Reactive Streams are coming in Java 9   
  63. 63. Parallel Streams
  64. 64. Be Warned! Some people, when confronted with a problem, think "I know, I’ll use multi-threading". Nothhw tpe yawrve o oblems.
  65. 65. Basic Parallel Streams
  66. 66. Returning to our Benchmark
  67. 67. Returning to our Benchmark NB: Units are operations per second so bigger is better 
  68. 68. Its Not That Easy
  69. 69. A More Complex Problem
  70. 70. A More Complex Problem NB: Units are operations per second so bigger is better 
  71. 71. Its Still Not That Easy
  72. 72. Converting the Code to REST
  73. 73. Sequential (GET /lines) Parallel (GET /linesParallel) 1 Thread 100 Requests 24 9 100 Threads 20 Requests 825 775 200 Threads 20 Requests 2086 2103 300 Threads 20 Requests 3598 3487 Average Times Via JMeter (Smaller is Better)
  74. 74. Its Still Still Not That Easy
  75. 75. Doug Lea et al… http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html
  76. 76. Best Practises for Parallel Streams • Parallel isn’t a panacea • Parallel isn’t a panacea • Parallel isn’t a panacea • ParParallelallel isn’tn’tn’t aaaaaaaaaaaa panacea • Use it when the data and task have the right ‘shape’ • Test correctly to confirm there is real world benefit
  77. 77. Testing Your Parallel Collections
  78. 78. OO Design Patterns and FP
  79. 79. • Patterns are fixes for issues in some style of programming • Places where the toolkit provided by your language is weak • Both OO and FP languages have associated patterns • The OO and FP styles of programming compliment one another • The use of one can remove the need for a pattern in the other • We have already seen an example • The ‘Optional’ type replaces the ‘Null Object’ Pattern • Having lambdas reduces the need for ‘objects as tasks’ • For example in the Command Pattern we can have a table of lambdas instead of a table of instances of anonymous types OO Design Patterns and FP
  80. 80. Best Practises for Design Patterns • Look again at your design and its use of patterns • Could these be reduced or removed via FP? • Pay particular attention were objects model tasks • Command • Observer • Strategy • Visitor
  81. 81. The Other Stuff
  82. 82. Best Practises for Other Features • Annotations can be repeated! • Refactor away ugliness • Use the new Date/Time API • JodaTime is now legacy • Be aware that annotations can appear just about anywhere • Benchmarking? • Code generation? • Prepare for modules in Java 9
  83. 83. Thanks for Watching 

×