Java8: Oogways final advise on Optional

Master Oogways enlighten us about Optional in his previous two sessions, and Now he set the stage for the final advise on Optional and believe me that is the most searchable questions on the internet about Optional, also many peoples mailed in OpenJDK forum regarding "Why Optional is not Serializable?" , Oogways promises to PO that he will try to give the best possible answers and we all keen to know the answer from Oogways as he is the wisest master in the world.
Let see the conversation happened beet ween PO an Oogways.

PO: Master I try to figure out why Optional is not serializable also searched on the internet but not found any compelling answers can you please enlighten me?
Master gives a calm look to Po and start his speech
Oogways: Before starting why Optional is not serializable I want to talk about an upcoming project in jdk10 which is Project Valhalla.
Project Valhalla: The slogan of project Valhalla i“Codes like a class, works like an int!” -- so, project Valhalla try to create a new user-defined datatype which can be treated as class i.e you can have data and behaviours tied into this but when that datatype runs on JVM it will act as primitives , i.e this datatype not stored in heap memory unlike Object and it does not have reference it will act as primitives like int, float -- it will stores in the stack memory. So obvious question comes
why so?
what are the benefits of that new datatype?
To answer this question we have to know a concept of ValueObject-- In Java sometimes we design some Objects which just carry value do nothing else-- act on the value, or preserve the state, this Object does not have any identity think about Integer what it does it wraps a primitive int value and why it is created?-- Just to support
java collection framework, It just a Wrapper Object, think about the ValueObject pattern in JEE or a Money Object(Value and currency), these are  used to pass values so conceptually these objects are not a proper object by definition, those objects are immutable in nature , and two objects are equals if their values are equal no identity check and obviously does not preserve a state which is the crux of an Object it acts as primitives more than Object so we called the Value Object, Now we all know there is cost associate to create Object, Even to make an Integer from int , it has to create a header(8-16 byte) and reference(4-8 bytes) in case of a reachable object, so instead of 4 bytes it takes 4+8+4=16 bytes minimum. also in case of the array of Integers, it has to traverse through pointers to fetch value as Integer array stores the references, not the value but in case of primitives it will store value locally in the stack so traversing is very fast, So the concept Project Valhalla it treats value type as primitives it gives us to create user-defined primitives.
Now I will tell you something about serialization.
Serialization: Serialization is a technique by which one can store the Object state in form of the stream so in future, we can reconstruct the state of the Object in same or another JVM from the stream. To achieve serialization is not a problem but Serialization has a huge maintenance cost, Because when we make an Object serializable we have to take care of the following
Back and forward JVM support: The Key feature of a serialization is it would be supported across any versions of Java including current and future release, so if an Object serializes in Java8 should be deserialized in java1.4 and vice versa so it supports backward and forward compatibility.So it has huge maintenance cost as various scenarios can occur where it may be broken, think about a situation if you want to add a new HAS-A relationship in your serializable Object and that class has been introduced in upper version of JDK how it would be deserialized in lower JVM as lower JVM does not know about that class.  Also in case deserializing it needs back-references to reconstruct the graph and need the Object reference. So Serialization hindering further modification of the Object, so maintaining Serialization is not a cup of tea.

Now, I come to the point why the Optional is not serializable, PO, If you look about the Optional it just wraps a value so it is a boxed class, If two Optional value is same we can say those are equals, so it treats like a Value type even in JavaDoc of Optional says
"This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided."
so it is clear Optional is a Value type and they know the Project Valhalla is in roadmap so obviously, they want to change Optional to a Value type (Identityless) when Project Valhalla onboard. And if they make them Serializable, now it needs to reside in heap memory and to deserialize the same need a reference but Project  Valhalla remove them from heap and stores in the stack so the question is how you deal with the same. there are lots of If and buts so they don't confident enough to make it serializable.
Another thing is the motto of Serialization is to reconstruct the state but Optional is a Valuetype and stateless so why they make it serializable it does not meet the criteria of serialization. Those are the reasons to not makeOptional serializable.
PO : I understood the Objective of not making Optional serializable but if they make it value type and make it serializable both by following technique, Suppose they make Optional as value type so it does not have any reference, but in the case of de-serialization  we can box them in an Object and make it present on heap memory, so it will be dubious nature, by default it is a value type but in case of deserialization it will act as an Object, by this we can solve the problem.
Oogways: PO, I like your thought, it proves that why I choose you as a Dragon Warrior. Really it is a compelling idea but think Optional is a Value type and in case of deserialization you want to make footprint in heap at that point it breaks the purpose of value type, To support serialization we unnecessary breaks the principle of project Valhalla, and bring back the problem which project Valhalla tries to solve, Optional is the category of Value Object to make it dubious nature to just support serialization is just a lame idea to me, To carrying the cost of serialization should have a compelling use cases, I don't see anything comelling in case of Optional.
PO: I understood master, Thanks for giving me a new direction I will learn more about project Valhalla and value type.
Oogway: Well, I am planning to give a session on Project Valhalla, you can attend that session.
PO: yes Master, I will and I bring my friend Shamik with me.
Oogways nodded his head.

Java8: Oogways Advice on Optional

While PO reading Java 8 Optional he has few question in mind and can not understand why Optional added in Java, How it saves us from the almighty villain null pointer Exception. So he goes to master Shifu, But the Irony is Shifu does not sure about How it will save Java users from the null pointer, but it is oogways foretold so they go to Oogways for advice on Optional.
I was there when the conversation happened, I will try to depict the conversation.
PO : Master oogways, I am really confused why Optional added in Java, I can't see any benefits , and I am bit skeptical how it saves from Nullpointer exception as it is nothing but a Container/Wrapper Object which held a reference to another Object, So the reference can be null and itself Optional wrapper class can be null, so I am confused what is the use case.
Oogway: From the birth of java the greatest sin is, The invention of null, Java tries to represent something absent as a null, but absent does not mean null it means not present. Java is a strong type language but null is such a value which can be assigned to any type, so it acts as a loose type variable, act as default value of reference, It is not blessing but a curse,
Every time we don't know what would be the returned Object, developers returns a null, and caller, unfortunately, bears the load of the null check for return value unless null pointer exception blows up the flow.
Let see a small example,

package com.example.optional;

import java.util.ArrayList;
import java.util.List;

public class OptionalTest {
private static List<String> nameList = new ArrayList<String>();
static{
nameList.add("Shamik");
nameList.add("Samir");
nameList.add("Swastika");
}

public String findName(String nameToFind){
return nameList.contains(nameToFind)?nameList.get(nameList.indexOf(nameToFind)):null;
}

public static void main(String[] args) {
OptionalTest test = new OptionalTest();
String searchedName = test.findName("Mayukh");
System.out.println(" Hi , " + searchedName.toUpperCase());
}


}
Here, The API developer exposes a method called findName, and silently return a null if the name is not found.  The caller of the API trust the API developer and called the method with an arbitrary name and try to print it in Uppercase. But it blows the caller's code with null pointer exception.
Whose fault is it Callers or API developer?

API Developers Perspective: When caller gives a name and that name is not found in nameList what should I do? return a blank string or return a String "NA" but if the caller says that they don't want "NA" or blank String, or One caller OK with the blank or "NA" String  and Other wants to handle the scenario by itself, so  as a developer when I am not sure what to return I always returns null. Yes, I am a good developer I can handle all the boundary cases.
Callers Perspective: findName is an API method I only command it to give me a search result "Tell Don't Ask", It is API method responsibility to handle boundary cases or cases if the searchable name is not found, It should give me a dummy implementation if the searchable name not found, like "NA". So I do not bother to check the return value, It is not my responsibility, so he skips the null check and programs blown up.

Really who's fault it is API developer or Caller?
Caller and Developer are right in their perspective, the confusion grows because API developer can't signal the caller, The return value may be present or absent. Null means no reference !!! (But How caller will  Understand current retuned reference not point to any Object instance?), so always it is caller responsibility to do a null check even if the value is present. null is not so expressive, to indicate caller a value is present or absent as it can be easily assigned to return value silently. So Optional step in here it tries to say value may be present or may be absent so caller it is your duty to check value is present or absent whereas null returns silently without informing the nature of the value.
Optional is acting as a Container, It holds the reference and provides some method to test the reference inside is present or absent.
Let see How we can return Optional with above example.

package com.example.optional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class OptionalTest {
private static List<String> nameList = new ArrayList<String>();
static{
nameList.add("Shamik");
nameList.add("Samir");
nameList.add("Swastika");
}

public Optional<String> findName(String nameToFind){
return nameList.contains(nameToFind)?Optional.of(nameList.get(nameList.indexOf(nameToFind))):Optional.empty();
}

public static void main(String[] args) {
OptionalTest test = new OptionalTest();
Optional<String> searchedName = test.findName("Mayukh");
if(searchedName.isPresent()){
System.out.println("HI,"+ searchedName.get());
}else{
System.out.println("Name not found");
}
}

}




Here, I use Optional.of() method which creates a new Optional object with the value passed in the 'of' method as a parameter, and if the value is not found in nameList I return and Empty optional which does not contain anything, don't say it contains a null, Empty represents the Value is absent, In this way we say to the caller, my method may gives you a result which does not contain anything so prepare for it.
PO : Master Oogways I understood your point but still I have  confusions, here caller has to check if(Optional.ispresent()) to get a value which is present but if caller forget to do this check, It gives you a NoSuchElement Exception, So what is the value to use optional -- seems it changed the null pointer exception to NoSuchElement Exception, nothing else, I don't see a point here to use Optional, It can't shield us from Null Pointer Exception.
Oogway: Ha Ha, That's why I choose you as a Dragon Warrior, You are so intelligent and to the point, You learned new things very quickly. Let me share you some thoughts,
Null is Omnipresent no one can never ever remove or defeat it completely, What we can do is protect ourselves from null, educate our Java villagers from the rage of nulls.
Optional is like a warning bell in the city, rather than nulls come silently, By Optional API developers always warned  Java Villagers/ or callers, Null can be entering your village at any point of time.
So my point is, till now only efficient villagers or callers understand when to use, not null check to escape from Null pointers rage but still in a complex call or lots of chained calls they fall in the null pointers trap. Optional tries to fix that it gives remind about absent values. Absent values can come so  protect your call from that or rather always use Optional.ispresent() check with Optional.get.
Optional does not remove the null pointer exception it warns caller to handle the absent scenarios.
It is not a Technical improvement rather it is a Conceptual improvement added into Java8 which educate java programmers to handle a scenario where value can be present or absent.

PO: I realize this Master Now tell me the Best practices of Optional.
Oogway: I am too late for today, Please come Tomorrow I will discuss best practices.

Conclusion: Oogway taught us a valuable lesson Optional is not a replacement for the null check rather it tries to say caller about the nature of the returns value and implicitly reminds caller to handle the absent cases. If Caller forgets to do that it will end up with the NoSuchElementException, which is a clear evidence you are trying to do an operation where the element/value is not present. It is a big conceptual improvement, it encourages caller to handle absent cases, unlike null return value where the caller has a confusion API developer already tackle the null value or I have to do this?