JavaOne- Lambdas Chops: Recipes for simpler more expressive code

“Lambdas Chops: Recipes for simpler more expressive code”

Speaker: Ian Robertson
slidehare.net/nainostrebor

For more blog posts from JavaOne, see the table of contents


Disclaimer: These are now the most performant way of doing things. If you have I/O or database code, it won’t be a significant difference.

Did one slide review of lambdas as “test” for whether kow enough to follow rest of session. [good idea]

Null safe navigation

  • In Groovy, a?.getX()?.getY()
  • Call method if object is non-null, otherwise just return null
  • Best route is to refactor to return Optional from the getters
  • If can’t refactor: Optional.ofNullable(employee).ap(Employee::getAddress).map(Address::getCity).orElse(null)
  • By chaining Optional can decide what to do

First non null

  • commons-lang has ObjectUtils.firstNonNull
  • Works will if values are cheap to provide
  • If expensive/time consuming, waiting for wasted work
  • firstNonNull(customer.getCart():getRecommendations, this::getBestSellers)
  • and firstNonNull now would have- Stream.of(values).map(Supplier:get).filter(Objects:nonNull).findFIrst().orElse(null)

Multi-method interfaces

  • Helper methods can create instances from one or more lambdas
  • Showed with SimpleFieVisitor. [i don’t see a lambda or method reference here. He mentioned a lambda, but there are no abstract methods now]

Exceptions

  • forEach(File::createNewFile) – doesn’t compile because throws IOException
  • Tried to solve in language and couldn’t.
  • Can catch exception in lambda and convert to runtime exception, but now code is long
  • jOOL library create companion interface that allows checked exceptions and converts to runtime exception
  • now write forEach(Unchecked.consumer(File::createNewFile))

Design Pattern

  • Dispose pattern – close in proper place [no null check in example]
  • Try-with-resources added in Java 7
  • Can forget; poor API that lets you forget
  • Must implement AutoCloseable
  • Can have close logic or lock/unlock in one place and pass lambda [still have to remember to call that]
  • Vavr (Java upside down) library has good library for lazy evaluation (double checked locking pattern) – pass lambda wih work

Type safety

  • Many APIs rely on String representation of method names
  • ex: commmons-beanutils takes method name for comparators. “stringly typed”
  • JDK added API that takes method reference Comparator.comparing(Person::getLastName).thenComparing(Person:getFirstName)
  • Now type safe

JUnit 5 Parameterized Tests

  • @MethodSource has “stringly typed” problem. Also, no way to know passing right # parameters and types
  • Alternatively can use @TestFactory and DynamicTests to have compile time type safety
  • Harder to read with tuples. Can improve further with helper method per combo and have tests use it.
  • [the lack of type safety doesn’t seem like a big deal here since run tests regularly so would know if mismatch. And parameterized tests are much easier to read ]
  • Wrote LambdataRunner to do this in JUnit 4

Best Practices

  • Have more single method interfaces. Provide static helper methods to create
  • Use existing interfaces where can instead of writing own. Easier because already know what it is
  • Avoid overloading method names to accept different lambas of same “shape”. Compiler says lamda ambigious and require lients to cast

My take: I really liked the discussion of pros and cons. And the emoticons were fun – happy, sad, angry, meh. I don’t like the JUnit example, but the rest sound like things I’d do/try.

JavaOne – Mockito 2 Cleaner Tests and Enhanced Productivity

“Mockito 2 Cleaner Tests and Enhanced Productivity”

Speaker: Szczepan Faber
[nice twitter handle – @mockitoguy]

For more blog posts from JavaOne, see the table of contents


Stats

  • Started in 2008 to overcome shortcomings of JMock and EasyMock
  • Mockito is number 3 Java library on github [not sure what this means]
  • 2016 – Mockito 2 came out
  • About 50 unique contributors

Conceptual

  • Talked about the importance of clean code
  • Plugged GTD (gettng things done) book
  • A good test tell you why it fails without using debugger
  • Used given/when/then format in tests – recommends actually writing those three words in comments; encourages to think about test that way
  • PowerMock extends/integrates with Mockito so can test legacy code

Live coding based on https://github.com/szczepiq/mockito-conferences-2017/tree/javaone

General

  • Fails with clear messages
  • Can click on line in console output message to go to it in IDE
  • JMock/EasyMock use strict mocking as default. Mockito is lenient by default so don’t have to put “unnecessary” code in the tests. [he did a demo of strict mocking simulation. I didn’t follow it. the code is here]
  • MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS) can change default. MockitoSession is the non-rule way to do so. Strict stubbing good as finds unused code. [confused; he just got through saying that strict mocking is bad. but it’s good for stubbing?].
  • Mockito 3 has strict stubs this as a default.
  • With strict stubs, don’t need to call verify – finds unused coe
  • There’s a way to enroll in strict stubs without the @Rule [didn’t show how]
  • Use shipkit for CD

My take: CodeRanch is in the process of migrating to Mockito (from a mix of Mockito/JMock and random other things). It was good to see best practices. I’m going to miss strict mocking. Trying to keep an open mind. I was able to follow most of it with my minimal experience with Mockito. Thought there’d have been a bit of intro up front. I left with questions though. For example, I don’t follow why strict mocks are bad but strict stubs are good. Which is conceptual so I was hoping to follow his point. And he has another session immediately after this one so can’t ask hallway questions.

JavaOne – 55 new features in Java 9

“55 new features in Java 9”

Speaker: Simon Ritter

For more blog posts from JavaOne, see the table of contents


  • Modularity/Jigsaw – JDK is 94 moudles. Java SE is 36 of them. Probably using sun.misc.Unsafe in open source library
  • Big kill switch now has options to permit/warn/debug (warn with stack trace)/deny(will be default at some point) illegal access
  • jlink – jaa linker so can build runtime specifically for your application. Creates directory structure for you that matches jdk but only wit the modules you need. java -list-modules shows what modules are in there. Version numbering information is for informational purposes only. Can’t use different versions for different parts of the code.
  • Static factory methods for List/Set/Map interfaces. Old way was to instantiate, add a bunch of elements and then call Collections.unmodifiableSet(). Now can just call Set.of(…) with 0-10 elements or varargs if have more and get an umodifiable collection
  • Stream enhancements – dropWHile/takeWhile (like skip/limit but with predicate rather than number), improved iterate to be more like a for loop, parallel Files.lines() as memory mapped and a stream from Optional with zero/one elements
  • multi-release jar files – use JDK 8 code in main jar file and then JDK 9 in the “9” diretory
  • jshell – REPL (read eval print loop) – good for simple prototyping
  • concurrency updates – reactive streams publish/subscribe framework, async nonblocking, Flow interfaces, SubmissionPublisher utility class.
  • CompleteableFuture additions (originally added in Java 8). Now has delays/timeouts, better support fr subclassing, static utility methods for minimalCompletionStage (read JavaDoc; confusing), failedStage, failedFuture [and one more]
  • Enhanced deprecation – forRemoval and since (not back ported consistently), jdeprscan command can produce report from jar or class file
  • Project Coin – single underscore not valid identifier (so in future can use _ in lambda instead of variable), priate method in interfaces, effectively final variables in tr-with-resources, allow @SafeVarars on private instance variables, diamond operate with anonyous classes
  • New standards – Unicode 7 (2834 new chars) and 8 (7716 new chars) support – added emojis, PKCS12 key stores by default, HTML 5 JavaDoc, etc
  • UTF-8 property files
  • DRBG based SecureRadom bit generators
  • XML catalog API upgraded standard
  • G1 is default garbage collector for servers (used to be parallel collectors), low pause, deals with bigger heaps
  • Better String performance – compact strings (use less space internally; don’t use 16 bits for chars that could be 8 bits), store interned strings in CDS archive to share char[] and String objects between VMs, String concatentaton to use invokedynamic (allows for future performance improvements at runtim)
  • Marlin graphics renderer – faster
  • A couple really low level VM performance things
  • JavaFX improvement
  • Segment Code cache – separates non-method, proiled and non-profiled code (enables future performance improvments)
  • Unified JVM and GC logging – using old options prevent JVM startup
  • Spin-wait hints. Small change to improve performance on x86, but Azul [where Simon works] proposed it showing openness of JEP.
  • Variable handles – API to replace parts of sun.misc.Unsafe. Used for fence operations (memory control/atomic operations preventing JVM from changing order of operations in code), VarHandle (low level objec)
  • AOT compilation – ahead of time compilation – experimental feature; need to turn on with UnlockExperimenalVMOptions. jaotc to comiple in this mode
  • Process API can get pid, arguments, start time, CPU usage and name if security manager allows
  • New version string format for java JDK major minor security patch. Will cange again post Java 10. No more 1.X
  • JDK/JRE file structure – only one bin directory no special jre direcory. tools.jar and rt.jar also went away.
  • Sarchable JavaDocs
  • Annotation pipeline – repeating annotations
  • Parser API for Nashorn – and spports ECMAScript 5.1
  • Disable SHA-1 certs mostly
  • Applets deprecated for removal in Java 10
  • A handful of APIs removed [not ommon ones]
  • Removed a few other things like hprof agent, jhat tool, old docs
  • Removed deprecated GC options

My take: He said up front that this talk is supposed to be an hour. Implying we won’t get to all 55 features. He didn’t sound rushed though so there wasn’t the problem from yesterday’s speaker with two much information. It was a good overview (or review) of the features. I learned some things like the eixstance of jdeprscan