Tuesday, October 20, 2015

Java 8 Lambdas, Streams, Options vs @NotNull type annotation

I have been using Java8 for a 6 months now and I am not impressed.

Even when you discount the fact that the JVM is not any faster than its predecessor  java 7, we still went ahead and upgraded.

Lambdas and Streams
lambdas and method references help to pass some succinct code but you loose the benefit of stack trace.
I think i would stick with strategy pattern and use lambdas only in streams.
Dont use lambdas if the code is complex, it hampers testing, and you also loose IDE support.

Option.
Since i started using relying on tests. I have not had a of null pointer exceptions in production in the last 5 years
And when you also consider good practices like using empty collections instead of null and equality checking on constants i.e"constant.equals(Varibable) and not the other way around. The incidence of  null pointers have greatly diminished.
In java 8. There is a also a feature call @NotNull coming soon. (JSR-308)
Using these techniques I am confident that i would not be using Option to wrap my logic to defend null pointers.

Update: 05/2023: No longer hold above views

Saturday, October 17, 2015

A final word about final, finally, finalize

Class final variables have to be set when they are declared or in  the constructor
Local final variables have to be set at declaration or later

Finalize is called during garbage collection


Finally is part of try.
try with resources eliminates  the need for catch. If these cause any exceptions (try-with-resources) swallows them silently.
try-with-resources can still have a finally block.

Bad practice is to throw new exceptions from finally. [We loose context of original exception]
try and finally are also used with locks.
Exceptions in finally are nasty
lock.lock();
try{
  //do critical section code, which may throw exception
} finally {
  lock.unlock();
}


Final classes cannot be subclassed, java have covarient returns types so for immutability final is required.

final methods cannot be overridden. (Saying dont override this)
static methods are not called polymorphically.

final class variables need to be set or set in a constructor
final local variables can be set once
final method argument are there to ensure that object references cannot be reset unintenionally.