archive-cr.com » CR » I » INFORMATECH.CR

Total: 292

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Memoized Fibonacci Numbers with Java 8 | Informatech CR Blog
    them we update the hash table with the results obtained This way the right branches will only perform a table lookup and the corresponding value will be retrieved from the hash table and not through a recursive calculation again Some of the new methods in the class Map in Java 8 simplify a lot the writing of such algorithm particularly the method computeIfAbsent key function Where the key would be the number for which we would like to look up the corresponding Fibonacci number and the function would be a lambda expression capable of triggering the recursive calculation if the corresponding value is not already present in the map So we can start by defining a map and putting the values in it for the base cases namely fibonnaci 0 and fibonacci 1 private static Map Integer Long memo new HashMap static memo put 0 0L fibonacci 0 memo put 1 1L fibonacci 1 And for the inductive step all we have to do is redefine our Fibonacci function as follows public static long fibonacci int x return memo computeIfAbsent x n fibonacci n 1 fibonacci n 2 As you can see the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map this recursive process will be triggered entirely for the left branch but the right branch will use the momoized values This represents a significant improvement Based on my subjective observation this improved recursive version was outstandingly faster for a discrete number like fibonacci 70 With this algorithm we can safely calculate up to fibonacci 92 without running into long overflow Even better to be sure that our algorithm would never cause overflows without letting the user know we could also use one of the new methods in Java 8 added to the Math class and which throws an ArithmeticException when overflow occurs So we could change our code as follows public static long fibonacci int x return memo computeIfAbsent x n Math addExact fibonacci n 1 fibonacci n 2 This method would start failing for fibonacci 93 If we need to go over 92 we would have to use BigInteger in our algorithm instead of just long Notice that the memozied example uses mutations therefore in order to use this code in a multithreaded environment we would first need to add some form of synchronization to the proposed code or use a different map implementation perhaps a ConcurrentHashMap which evidently may impact performance as well Arguably this would still be better than the original recursive algorithm Share this Email Facebook Twitter Like this Like Loading Related May 8 2013 by Edwin Dalorzo Categories Java Tags fibonacci java 7 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Java 8 Optional Objects 6 Days with Windows Phone 7 thoughts on Memoized Fibonacci Numbers with Java 8 Caesar Ralf Franz Hoppen says May 13 2013 at 10 45 am This is a

    Original URL path: http://blog.informatech.cr/2013/05/08/memoized-fibonacci-numbers-with-java-8/?replytocom=2370 (2015-08-19)
    Open archived version from archive


  • Memoized Fibonacci Numbers with Java 8 | Informatech CR Blog
    them we update the hash table with the results obtained This way the right branches will only perform a table lookup and the corresponding value will be retrieved from the hash table and not through a recursive calculation again Some of the new methods in the class Map in Java 8 simplify a lot the writing of such algorithm particularly the method computeIfAbsent key function Where the key would be the number for which we would like to look up the corresponding Fibonacci number and the function would be a lambda expression capable of triggering the recursive calculation if the corresponding value is not already present in the map So we can start by defining a map and putting the values in it for the base cases namely fibonnaci 0 and fibonacci 1 private static Map Integer Long memo new HashMap static memo put 0 0L fibonacci 0 memo put 1 1L fibonacci 1 And for the inductive step all we have to do is redefine our Fibonacci function as follows public static long fibonacci int x return memo computeIfAbsent x n fibonacci n 1 fibonacci n 2 As you can see the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map this recursive process will be triggered entirely for the left branch but the right branch will use the momoized values This represents a significant improvement Based on my subjective observation this improved recursive version was outstandingly faster for a discrete number like fibonacci 70 With this algorithm we can safely calculate up to fibonacci 92 without running into long overflow Even better to be sure that our algorithm would never cause overflows without letting the user know we could also use one of the new methods in Java 8 added to the Math class and which throws an ArithmeticException when overflow occurs So we could change our code as follows public static long fibonacci int x return memo computeIfAbsent x n Math addExact fibonacci n 1 fibonacci n 2 This method would start failing for fibonacci 93 If we need to go over 92 we would have to use BigInteger in our algorithm instead of just long Notice that the memozied example uses mutations therefore in order to use this code in a multithreaded environment we would first need to add some form of synchronization to the proposed code or use a different map implementation perhaps a ConcurrentHashMap which evidently may impact performance as well Arguably this would still be better than the original recursive algorithm Share this Email Facebook Twitter Like this Like Loading Related May 8 2013 by Edwin Dalorzo Categories Java Tags fibonacci java 7 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Java 8 Optional Objects 6 Days with Windows Phone 7 thoughts on Memoized Fibonacci Numbers with Java 8 Caesar Ralf Franz Hoppen says May 13 2013 at 10 45 am This is a

    Original URL path: http://blog.informatech.cr/2013/05/08/memoized-fibonacci-numbers-with-java-8/?replytocom=2372 (2015-08-19)
    Open archived version from archive

  • Memoized Fibonacci Numbers with Java 8 | Informatech CR Blog
    find them we update the hash table with the results obtained This way the right branches will only perform a table lookup and the corresponding value will be retrieved from the hash table and not through a recursive calculation again Some of the new methods in the class Map in Java 8 simplify a lot the writing of such algorithm particularly the method computeIfAbsent key function Where the key would be the number for which we would like to look up the corresponding Fibonacci number and the function would be a lambda expression capable of triggering the recursive calculation if the corresponding value is not already present in the map So we can start by defining a map and putting the values in it for the base cases namely fibonnaci 0 and fibonacci 1 private static Map Integer Long memo new HashMap static memo put 0 0L fibonacci 0 memo put 1 1L fibonacci 1 And for the inductive step all we have to do is redefine our Fibonacci function as follows public static long fibonacci int x return memo computeIfAbsent x n fibonacci n 1 fibonacci n 2 As you can see the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map this recursive process will be triggered entirely for the left branch but the right branch will use the momoized values This represents a significant improvement Based on my subjective observation this improved recursive version was outstandingly faster for a discrete number like fibonacci 70 With this algorithm we can safely calculate up to fibonacci 92 without running into long overflow Even better to be sure that our algorithm would never cause overflows without letting the user know we could also use one of the new methods in Java 8 added to the Math class and which throws an ArithmeticException when overflow occurs So we could change our code as follows public static long fibonacci int x return memo computeIfAbsent x n Math addExact fibonacci n 1 fibonacci n 2 This method would start failing for fibonacci 93 If we need to go over 92 we would have to use BigInteger in our algorithm instead of just long Notice that the memozied example uses mutations therefore in order to use this code in a multithreaded environment we would first need to add some form of synchronization to the proposed code or use a different map implementation perhaps a ConcurrentHashMap which evidently may impact performance as well Arguably this would still be better than the original recursive algorithm Share this Email Facebook Twitter Like this Like Loading Related May 8 2013 by Edwin Dalorzo Categories Java Tags fibonacci java 7 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Java 8 Optional Objects 6 Days with Windows Phone 7 thoughts on Memoized Fibonacci Numbers with Java 8 Caesar Ralf Franz Hoppen says May 13 2013 at 10 45 am This is

    Original URL path: http://blog.informatech.cr/2013/05/08/memoized-fibonacci-numbers-with-java-8/?replytocom=2528 (2015-08-19)
    Open archived version from archive

  • Java 8 Optional Objects | Informatech CR Blog
    you can see option is a data type with two constructors one of them stores nothing i e NONE whereas the other is capable of storing a polymorphic value of some value type a where a is just a placeholder for the actual type Under this model the piece of code we wrote before in Java to find a fruit by its name could be rewritten in SML as follows fun find name fruits case fruits of NONE Fruit s fs if s name then SOME Fruit s else find name fs There are several ways to achieve this in SML this example just shows one way to do it The important point here is that there is no such thing as null instead a value NONE is returned when nothing is found 3 and a value SOME fruit is returned otherwise 5 When a programmer uses this find method he knows that it returns an option type value and therefore the programmer is forced to check the nature of the value obtained to see if it is either NONE 6 or SOME fruit 7 somewhat like this let val fruits Fruit apple Fruit grape Fruit orange val found find grape fruits in case found of NONE print Nothing found SOME Fruit f print Found fruit f end Having to check for the true nature of the returned option makes it impossible to misinterpret the result Java Optional Types It s a joy that finally in Java 8 we ll have a new class called Optional that allows us to implement a similar idiom as that from the functional world As in the case of of SML the Optional type is polymorphic and may contain a value or be empty So we could rewrite our previous code snippet as follows public static Optional Fruit find String name List Fruit fruits for Fruit fruit fruits if fruit getName equals name return Optional of fruit return Optional empty As you can see the method now returns an Optional reference 1 if something is found the Optional object is constructed with a value 4 otherwise is constructed empty 7 And the programmer using this code would do something as follows List Fruit fruits asList new Fruit apple new Fruit grape new Fruit orange Optional Fruit found find lemon fruits if found isPresent Fruit fruit found get String name fruit getName Now it is made evident in the type of the find method that it returns an optional value 5 and the user of this method has to program his code accordingly 6 7 So we see that the adoption of this functional idiom is likely to make our code safer less prompt to null dereferencing problems and as a result more robust and less error prone Of course it is not a perfect solution because after all Optional references can also be erroneously set to null references but I would expect that programmers stick to the convention of not passing null references where an optional object is expected pretty much as we today consider a good practice not to pass a null reference where a collection or an array is expected in these cases the correct is to pass an empty array or collection The point here is that now we have a mechanism in the API that we can use to make explicit that for a given reference we may not have a value to assign it and the user is forced by the API to verify that Quoting an article I reference later about the use of optional objects in the Guava Collections framework Besides the increase in readability that comes from giving null a name the biggest advantage of Optional is its idiot proof ness It forces you to actively think about the absent case if you want your program to compile at all since you have to actively unwrap the Optional and address that case Other Convenient Methods As of the today besides the static methods of and empty explained above the Optional class contains the following convenient instance methods ifPresent Which returns true if a value is present in the optional get Which returns a reference to the item contained in the optional object if present otherwise throws a NoSuchElementException ifPresent Consumer T consumer Which passess the optional value if present to the provided Consumer which could be implemented through a lambda expression or method reference orElse T other Which returns the value if present otherwise returns the value in other orElseGet Supplier T other Which returns the value if present otherwise returns the value provided by the Supplier which could be implemented with a lambda expression or method reference orElseThrow Supplier T exceptionSupplier Which returns the value if present otherwise throws the exception provided by the Supplier which could be implemented with a lambda expression or method reference Avoiding Boilerplate Presence Checks We can use some of the convenient methods mentioned above to avoid the need of having to check if a value is present in the optional object For instance we may want to use a default fruit value if nothing is found let s say that we would like to use a Kiwi So we could rewrite our previous code like this Optional Fruit found find lemon fruits String name found orElse new Fruit Kiwi getName In this other example the code prints the fruit name to the main output if the fruit is present In this case we implement the Consumer with a lambda expression Optional Fruit found find lemon fruits found ifPresent f System out println f getName This other piece of code uses a lambda expression to provide a Supplier which can ultimately provide a default answer if the optional object is empty Optional Fruit found find lemon fruits Fruit fruit found orElseGet new Fruit Lemon Clearly we can see that these convenient methods simplify a lot having to work with the optional objects So What s Wrong with Optional The question we face is will Optional get rid of null references And the answer is an emphatic no So detractors immediately question its value asking then what is it good for that we couldn t do by other means already Unlike functional languages like SML o Haskell which never had the concept of null references in Java we cannot simply get rid of the null references that have historically existed This will continue to exist and they arguably have their proper uses just to mention an example three valued logic I doubt that the intention with the Optional class is to replace every single nullable reference but to help in the creation of more robust APIs in which just by reading the signature of a method we could tell if we can expect an optional value or not and force the programmer to use this value accordingly But ultimately Optional will be just another reference and subject to same weaknesses of every other reference in the language It is quite evident that Optional is not going to save the day How these optional objects are supposed to be used or whether they are valuable or not in Java has been the matter of a heated debate in the project lambda mailing list From the detractors we hear interesting arguments like The fact that other alternatives exist i e the Eclipse IDE supports a set of proprietary annotations for static analysis of nullability the JSR 305 with annotations like Nullable and NonNull Some would like it to be usable as in the functional world which is not entirely possible in Java since the language lacks many features existing in functional programming languages like SML or Haskell i e pattern matching Others argue about how it is impossible to retrofit preexisting code to use this idiom i e List get Object which will continue to return null And some complain about the fact that the lack of language support for optional values creates a potential scenario in which Optional could be used inconsistently in the APIs by this creating incompatibilities pretty much like the ones we will have with the rest of the Java API which cannot be retrofitted to use the new Optional class A compelling argument is that if the programmer invokes the get method in an optional object if it is empty it will raise a NoSuchElementException which is pretty much the same problem that we have with nulls just with a different exception So it would appear that the benefits of Optional are really questionable and are probably constrained to improving readability and enforcing public interface contracts Optional Objects in the Stream API Irrespective of the debate the optional objects are here to stay and they are already being used in the new Stream API in methods like findFirst findAny max and min It could be worth mentioning that a very similar class has been in used in the successful Guava Collections Framework For instance consider the following example where we extract from a stream the last fruit name in alphabetical order Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit max fruits max comparing Fruit getName if max isPresent String fruitName max get getName grape Or this another one in which we obtain the first fruit in a stream Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit first fruits findFirst if first isPresent String fruitName first get getName apple Ceylon Programming Language and Optional Types Recently I started to play a bit with the Ceylon programming language since I was doing a research for another post that I am planning to publish soon in this blog I must say I am not a big fan of Ceylon but still I found particularly interesting that in Ceylon this concept of optional values is taken a bit further and the language itself offers some syntactic sugar for this idiom In this language we can mark any type with a question mark in order to indicate that its type is an optional type For instance this find function would be very similar to our original Java version but this time returning an optional Fruit reference 1 Also notice that a null value is compatible with the optional Fruit reference 7 Fruit find String name List Fruit fruits for Fruit fruit in fruits if fruit name name return fruit return null And we could use it with this Ceylon code similar to our last Java snippet in which we used an optional value List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find lemon fruits print fruit else Fruit Kiwi name Notice the use of the else keyword here is pretty similar to the method orElse in the Java 8 Optional class Also notice that the syntax is similar to the declaration of C nullable types but it means something totally different in Ceylon It may be worth mentioning that Kotlin the programming language under development by Jetbrains has a similar feature related to null safety so maybe we are before a trend in programming languages An alternative way of doing this would have been like this List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find apple fruits if exists fruit String fruitName fruit name print The found fruit is fruitName else Notice the use of the exists keyword here 3 serves the same purpose as the isPresent method invocation in the Java Optional class The great advantage of Ceylon over Java is that they can use this optional type in the APIs since the beginning within the realm of their language they won t have to deal with incompatibilities and it can be fully supported everywhere perhaps their problem will be in their integration with the rest of the Java APIs but I have not studied this yet Hopefully in future releases of Java this same syntactic sugar from Ceylon and Kotlin will also be made available in the Java programming language perhaps using under the hood this new Optional class introduced in Java 8 Further Reading Java Language Specification The Billion Dollars Mistake Refactoring Catalog Ceylon Programming Language Kotlin Programming Language C Nullable Types Avoid Using Null Guava Framework More Discussion on Java s Optional Java Infinite Streams Java Streams API Preview Java Streams Preview vs Net High Order Programming with LINQ Share this Email Facebook Twitter Like this Like Loading Related April 10 2013 by Edwin Dalorzo Categories Java Programming Tags ceylon java null pointer programming sml 23 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Overview Of The Task Parallel Library TPL Memoized Fibonacci Numbers with Java 8 23 thoughts on Java 8 Optional Objects lukaseder says April 11 2013 at 3 15 pm Very nice research Well you know that blank and initial states were already known to Turing 1 You could also argue that the neutral or zero state were required in the Babbage Engine 2 which dates back to Ada of Lovelace in the 1800 s On the other hand mathematicians also prefer to distinguish nothing from the empty set 3 which is a set with nothing inside This compares well with NONE and SOME Anyway I ve given Java s Optional some thought I m really not sure if I m going to like it Since Java is so incredibly backwards compatible none of the existing APIs will be retrofitted to return Optional e g interface List Optional get int index So not only as you said can you assign null to an Optional variable but the absence of Optional doesn t guarantee the semantics of SOME When we mix the two ways of thinking we will wind up with two checks instead of one 1 from me to Java s solution unlike Ceylon 1 http en wikipedia org wiki Turing machine 2 http www fourmilab ch babbage sketch html 3 http en wikipedia org wiki Empty set Reply Edwin Dalorzo says April 11 2013 at 4 16 pm Great comment Lukas These are really good references and comparisons with other mathematical models It will take me some time to go over all these but I will certainly enjoy it You are totally right as long as the null reference exists there is no way that something like Optional will get rid of null dereferencing problem in certain cases like the one you mention with two null checks it could make it worse I still believe that in the case of return values it makes the APIs more explicit Perhaps we cannot retrofit the uncountable lines of code already using other mechanisms like the List example you gave but from this day on at least we have an alternative Like you I also think the Ceylon solution is kind of neat although ironically they did not get rid of null entirely I still have much to learn in this subject but the exercise of writing this article helped me a lot to understand this classical problem and your references will enriched the discussion Reply lukaseder says April 12 2013 at 7 14 am Hehe I actually wasn t 100 sure about Turing and Ada But I was sure those guys must ve suffered from NullTapeExceptions The only ones who probably didn t have this problem were the Romans who started counting at I II III IV V They couldn t model the absense of apples and pears on their markets Yeah Ceylon cannot get rid of null easily if they want to be interoperable with Java Although there seem to be ways as this interesting article displays claiming to be able to get rid of Java s null in Scala http dysphoria net scala sip nulls xhtml Nick G NicolasGuzCa says April 14 2013 at 8 43 pm Great Article Using Optional Objects will definitely improve Java development I had one of those problems you mentioned and went days trying to figure what was wrong In the end I programmed a series of try catch to help me with the nulls but it s not the most optimal solution Reply DvH says April 15 2013 at 7 19 am IMO the Optional class is just additional baggage I immediately think of those creative folks who find good reasons to return Optional sometimes and null at other times I d prefer and use the Nullable annotation Reply Edwin Dalorzo says April 15 2013 at 5 43 pm Like it or not the new Optional class will be part of the JDK 8 Stream APIs so getting some familiarity with it and its purpose could be valuable even if you intend to use other alternatives in your own APIs Also as it gets more popular chances are that APIs created by other developers using JDK 8 or later version will contain this new class and you would still be forced to use it even when you wouldn t expose it in your own APIs Reply Jack Wright says April 15 2013 at 1 33 pm It s nice to see java is finally getting the maybe monad http en wikipedia org wiki Monad functional programming The Maybe monad I believe from a traditional OO background it is hard at first glance to understand why this is really useful I personally would like to see more monads like this in java much like they already exist in scala It is true that Optional value could be null though I would say by the very contract of saying something is contained in optional that it should be unnecessary to add any other declarations as they would be redundant Scala does provide some useful Syntactic sugar for dealing with results that might be null and wrapping them in option ie Option apply will check for null and return None As far as syntactic sugar goes what I would really prefer to see is something like scala s for comprehension

    Original URL path: http://blog.informatech.cr/2013/04/10/java-optional-objects/?replytocom=1276 (2015-08-19)
    Open archived version from archive

  • Java 8 Optional Objects | Informatech CR Blog
    you can see option is a data type with two constructors one of them stores nothing i e NONE whereas the other is capable of storing a polymorphic value of some value type a where a is just a placeholder for the actual type Under this model the piece of code we wrote before in Java to find a fruit by its name could be rewritten in SML as follows fun find name fruits case fruits of NONE Fruit s fs if s name then SOME Fruit s else find name fs There are several ways to achieve this in SML this example just shows one way to do it The important point here is that there is no such thing as null instead a value NONE is returned when nothing is found 3 and a value SOME fruit is returned otherwise 5 When a programmer uses this find method he knows that it returns an option type value and therefore the programmer is forced to check the nature of the value obtained to see if it is either NONE 6 or SOME fruit 7 somewhat like this let val fruits Fruit apple Fruit grape Fruit orange val found find grape fruits in case found of NONE print Nothing found SOME Fruit f print Found fruit f end Having to check for the true nature of the returned option makes it impossible to misinterpret the result Java Optional Types It s a joy that finally in Java 8 we ll have a new class called Optional that allows us to implement a similar idiom as that from the functional world As in the case of of SML the Optional type is polymorphic and may contain a value or be empty So we could rewrite our previous code snippet as follows public static Optional Fruit find String name List Fruit fruits for Fruit fruit fruits if fruit getName equals name return Optional of fruit return Optional empty As you can see the method now returns an Optional reference 1 if something is found the Optional object is constructed with a value 4 otherwise is constructed empty 7 And the programmer using this code would do something as follows List Fruit fruits asList new Fruit apple new Fruit grape new Fruit orange Optional Fruit found find lemon fruits if found isPresent Fruit fruit found get String name fruit getName Now it is made evident in the type of the find method that it returns an optional value 5 and the user of this method has to program his code accordingly 6 7 So we see that the adoption of this functional idiom is likely to make our code safer less prompt to null dereferencing problems and as a result more robust and less error prone Of course it is not a perfect solution because after all Optional references can also be erroneously set to null references but I would expect that programmers stick to the convention of not passing null references where an optional object is expected pretty much as we today consider a good practice not to pass a null reference where a collection or an array is expected in these cases the correct is to pass an empty array or collection The point here is that now we have a mechanism in the API that we can use to make explicit that for a given reference we may not have a value to assign it and the user is forced by the API to verify that Quoting an article I reference later about the use of optional objects in the Guava Collections framework Besides the increase in readability that comes from giving null a name the biggest advantage of Optional is its idiot proof ness It forces you to actively think about the absent case if you want your program to compile at all since you have to actively unwrap the Optional and address that case Other Convenient Methods As of the today besides the static methods of and empty explained above the Optional class contains the following convenient instance methods ifPresent Which returns true if a value is present in the optional get Which returns a reference to the item contained in the optional object if present otherwise throws a NoSuchElementException ifPresent Consumer T consumer Which passess the optional value if present to the provided Consumer which could be implemented through a lambda expression or method reference orElse T other Which returns the value if present otherwise returns the value in other orElseGet Supplier T other Which returns the value if present otherwise returns the value provided by the Supplier which could be implemented with a lambda expression or method reference orElseThrow Supplier T exceptionSupplier Which returns the value if present otherwise throws the exception provided by the Supplier which could be implemented with a lambda expression or method reference Avoiding Boilerplate Presence Checks We can use some of the convenient methods mentioned above to avoid the need of having to check if a value is present in the optional object For instance we may want to use a default fruit value if nothing is found let s say that we would like to use a Kiwi So we could rewrite our previous code like this Optional Fruit found find lemon fruits String name found orElse new Fruit Kiwi getName In this other example the code prints the fruit name to the main output if the fruit is present In this case we implement the Consumer with a lambda expression Optional Fruit found find lemon fruits found ifPresent f System out println f getName This other piece of code uses a lambda expression to provide a Supplier which can ultimately provide a default answer if the optional object is empty Optional Fruit found find lemon fruits Fruit fruit found orElseGet new Fruit Lemon Clearly we can see that these convenient methods simplify a lot having to work with the optional objects So What s Wrong with Optional The question we face is will Optional get rid of null references And the answer is an emphatic no So detractors immediately question its value asking then what is it good for that we couldn t do by other means already Unlike functional languages like SML o Haskell which never had the concept of null references in Java we cannot simply get rid of the null references that have historically existed This will continue to exist and they arguably have their proper uses just to mention an example three valued logic I doubt that the intention with the Optional class is to replace every single nullable reference but to help in the creation of more robust APIs in which just by reading the signature of a method we could tell if we can expect an optional value or not and force the programmer to use this value accordingly But ultimately Optional will be just another reference and subject to same weaknesses of every other reference in the language It is quite evident that Optional is not going to save the day How these optional objects are supposed to be used or whether they are valuable or not in Java has been the matter of a heated debate in the project lambda mailing list From the detractors we hear interesting arguments like The fact that other alternatives exist i e the Eclipse IDE supports a set of proprietary annotations for static analysis of nullability the JSR 305 with annotations like Nullable and NonNull Some would like it to be usable as in the functional world which is not entirely possible in Java since the language lacks many features existing in functional programming languages like SML or Haskell i e pattern matching Others argue about how it is impossible to retrofit preexisting code to use this idiom i e List get Object which will continue to return null And some complain about the fact that the lack of language support for optional values creates a potential scenario in which Optional could be used inconsistently in the APIs by this creating incompatibilities pretty much like the ones we will have with the rest of the Java API which cannot be retrofitted to use the new Optional class A compelling argument is that if the programmer invokes the get method in an optional object if it is empty it will raise a NoSuchElementException which is pretty much the same problem that we have with nulls just with a different exception So it would appear that the benefits of Optional are really questionable and are probably constrained to improving readability and enforcing public interface contracts Optional Objects in the Stream API Irrespective of the debate the optional objects are here to stay and they are already being used in the new Stream API in methods like findFirst findAny max and min It could be worth mentioning that a very similar class has been in used in the successful Guava Collections Framework For instance consider the following example where we extract from a stream the last fruit name in alphabetical order Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit max fruits max comparing Fruit getName if max isPresent String fruitName max get getName grape Or this another one in which we obtain the first fruit in a stream Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit first fruits findFirst if first isPresent String fruitName first get getName apple Ceylon Programming Language and Optional Types Recently I started to play a bit with the Ceylon programming language since I was doing a research for another post that I am planning to publish soon in this blog I must say I am not a big fan of Ceylon but still I found particularly interesting that in Ceylon this concept of optional values is taken a bit further and the language itself offers some syntactic sugar for this idiom In this language we can mark any type with a question mark in order to indicate that its type is an optional type For instance this find function would be very similar to our original Java version but this time returning an optional Fruit reference 1 Also notice that a null value is compatible with the optional Fruit reference 7 Fruit find String name List Fruit fruits for Fruit fruit in fruits if fruit name name return fruit return null And we could use it with this Ceylon code similar to our last Java snippet in which we used an optional value List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find lemon fruits print fruit else Fruit Kiwi name Notice the use of the else keyword here is pretty similar to the method orElse in the Java 8 Optional class Also notice that the syntax is similar to the declaration of C nullable types but it means something totally different in Ceylon It may be worth mentioning that Kotlin the programming language under development by Jetbrains has a similar feature related to null safety so maybe we are before a trend in programming languages An alternative way of doing this would have been like this List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find apple fruits if exists fruit String fruitName fruit name print The found fruit is fruitName else Notice the use of the exists keyword here 3 serves the same purpose as the isPresent method invocation in the Java Optional class The great advantage of Ceylon over Java is that they can use this optional type in the APIs since the beginning within the realm of their language they won t have to deal with incompatibilities and it can be fully supported everywhere perhaps their problem will be in their integration with the rest of the Java APIs but I have not studied this yet Hopefully in future releases of Java this same syntactic sugar from Ceylon and Kotlin will also be made available in the Java programming language perhaps using under the hood this new Optional class introduced in Java 8 Further Reading Java Language Specification The Billion Dollars Mistake Refactoring Catalog Ceylon Programming Language Kotlin Programming Language C Nullable Types Avoid Using Null Guava Framework More Discussion on Java s Optional Java Infinite Streams Java Streams API Preview Java Streams Preview vs Net High Order Programming with LINQ Share this Email Facebook Twitter Like this Like Loading Related April 10 2013 by Edwin Dalorzo Categories Java Programming Tags ceylon java null pointer programming sml 23 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Overview Of The Task Parallel Library TPL Memoized Fibonacci Numbers with Java 8 23 thoughts on Java 8 Optional Objects lukaseder says April 11 2013 at 3 15 pm Very nice research Well you know that blank and initial states were already known to Turing 1 You could also argue that the neutral or zero state were required in the Babbage Engine 2 which dates back to Ada of Lovelace in the 1800 s On the other hand mathematicians also prefer to distinguish nothing from the empty set 3 which is a set with nothing inside This compares well with NONE and SOME Anyway I ve given Java s Optional some thought I m really not sure if I m going to like it Since Java is so incredibly backwards compatible none of the existing APIs will be retrofitted to return Optional e g interface List Optional get int index So not only as you said can you assign null to an Optional variable but the absence of Optional doesn t guarantee the semantics of SOME When we mix the two ways of thinking we will wind up with two checks instead of one 1 from me to Java s solution unlike Ceylon 1 http en wikipedia org wiki Turing machine 2 http www fourmilab ch babbage sketch html 3 http en wikipedia org wiki Empty set Reply Edwin Dalorzo says April 11 2013 at 4 16 pm Great comment Lukas These are really good references and comparisons with other mathematical models It will take me some time to go over all these but I will certainly enjoy it You are totally right as long as the null reference exists there is no way that something like Optional will get rid of null dereferencing problem in certain cases like the one you mention with two null checks it could make it worse I still believe that in the case of return values it makes the APIs more explicit Perhaps we cannot retrofit the uncountable lines of code already using other mechanisms like the List example you gave but from this day on at least we have an alternative Like you I also think the Ceylon solution is kind of neat although ironically they did not get rid of null entirely I still have much to learn in this subject but the exercise of writing this article helped me a lot to understand this classical problem and your references will enriched the discussion Reply lukaseder says April 12 2013 at 7 14 am Hehe I actually wasn t 100 sure about Turing and Ada But I was sure those guys must ve suffered from NullTapeExceptions The only ones who probably didn t have this problem were the Romans who started counting at I II III IV V They couldn t model the absense of apples and pears on their markets Yeah Ceylon cannot get rid of null easily if they want to be interoperable with Java Although there seem to be ways as this interesting article displays claiming to be able to get rid of Java s null in Scala http dysphoria net scala sip nulls xhtml Nick G NicolasGuzCa says April 14 2013 at 8 43 pm Great Article Using Optional Objects will definitely improve Java development I had one of those problems you mentioned and went days trying to figure what was wrong In the end I programmed a series of try catch to help me with the nulls but it s not the most optimal solution Reply DvH says April 15 2013 at 7 19 am IMO the Optional class is just additional baggage I immediately think of those creative folks who find good reasons to return Optional sometimes and null at other times I d prefer and use the Nullable annotation Reply Edwin Dalorzo says April 15 2013 at 5 43 pm Like it or not the new Optional class will be part of the JDK 8 Stream APIs so getting some familiarity with it and its purpose could be valuable even if you intend to use other alternatives in your own APIs Also as it gets more popular chances are that APIs created by other developers using JDK 8 or later version will contain this new class and you would still be forced to use it even when you wouldn t expose it in your own APIs Reply Jack Wright says April 15 2013 at 1 33 pm It s nice to see java is finally getting the maybe monad http en wikipedia org wiki Monad functional programming The Maybe monad I believe from a traditional OO background it is hard at first glance to understand why this is really useful I personally would like to see more monads like this in java much like they already exist in scala It is true that Optional value could be null though I would say by the very contract of saying something is contained in optional that it should be unnecessary to add any other declarations as they would be redundant Scala does provide some useful Syntactic sugar for dealing with results that might be null and wrapping them in option ie Option apply will check for null and return None As far as syntactic sugar goes what I would really prefer to see is something like scala s for comprehension

    Original URL path: http://blog.informatech.cr/2013/04/10/java-optional-objects/?replytocom=1281 (2015-08-19)
    Open archived version from archive

  • Java 8 Optional Objects | Informatech CR Blog
    can see option is a data type with two constructors one of them stores nothing i e NONE whereas the other is capable of storing a polymorphic value of some value type a where a is just a placeholder for the actual type Under this model the piece of code we wrote before in Java to find a fruit by its name could be rewritten in SML as follows fun find name fruits case fruits of NONE Fruit s fs if s name then SOME Fruit s else find name fs There are several ways to achieve this in SML this example just shows one way to do it The important point here is that there is no such thing as null instead a value NONE is returned when nothing is found 3 and a value SOME fruit is returned otherwise 5 When a programmer uses this find method he knows that it returns an option type value and therefore the programmer is forced to check the nature of the value obtained to see if it is either NONE 6 or SOME fruit 7 somewhat like this let val fruits Fruit apple Fruit grape Fruit orange val found find grape fruits in case found of NONE print Nothing found SOME Fruit f print Found fruit f end Having to check for the true nature of the returned option makes it impossible to misinterpret the result Java Optional Types It s a joy that finally in Java 8 we ll have a new class called Optional that allows us to implement a similar idiom as that from the functional world As in the case of of SML the Optional type is polymorphic and may contain a value or be empty So we could rewrite our previous code snippet as follows public static Optional Fruit find String name List Fruit fruits for Fruit fruit fruits if fruit getName equals name return Optional of fruit return Optional empty As you can see the method now returns an Optional reference 1 if something is found the Optional object is constructed with a value 4 otherwise is constructed empty 7 And the programmer using this code would do something as follows List Fruit fruits asList new Fruit apple new Fruit grape new Fruit orange Optional Fruit found find lemon fruits if found isPresent Fruit fruit found get String name fruit getName Now it is made evident in the type of the find method that it returns an optional value 5 and the user of this method has to program his code accordingly 6 7 So we see that the adoption of this functional idiom is likely to make our code safer less prompt to null dereferencing problems and as a result more robust and less error prone Of course it is not a perfect solution because after all Optional references can also be erroneously set to null references but I would expect that programmers stick to the convention of not passing null references where an optional object is expected pretty much as we today consider a good practice not to pass a null reference where a collection or an array is expected in these cases the correct is to pass an empty array or collection The point here is that now we have a mechanism in the API that we can use to make explicit that for a given reference we may not have a value to assign it and the user is forced by the API to verify that Quoting an article I reference later about the use of optional objects in the Guava Collections framework Besides the increase in readability that comes from giving null a name the biggest advantage of Optional is its idiot proof ness It forces you to actively think about the absent case if you want your program to compile at all since you have to actively unwrap the Optional and address that case Other Convenient Methods As of the today besides the static methods of and empty explained above the Optional class contains the following convenient instance methods ifPresent Which returns true if a value is present in the optional get Which returns a reference to the item contained in the optional object if present otherwise throws a NoSuchElementException ifPresent Consumer T consumer Which passess the optional value if present to the provided Consumer which could be implemented through a lambda expression or method reference orElse T other Which returns the value if present otherwise returns the value in other orElseGet Supplier T other Which returns the value if present otherwise returns the value provided by the Supplier which could be implemented with a lambda expression or method reference orElseThrow Supplier T exceptionSupplier Which returns the value if present otherwise throws the exception provided by the Supplier which could be implemented with a lambda expression or method reference Avoiding Boilerplate Presence Checks We can use some of the convenient methods mentioned above to avoid the need of having to check if a value is present in the optional object For instance we may want to use a default fruit value if nothing is found let s say that we would like to use a Kiwi So we could rewrite our previous code like this Optional Fruit found find lemon fruits String name found orElse new Fruit Kiwi getName In this other example the code prints the fruit name to the main output if the fruit is present In this case we implement the Consumer with a lambda expression Optional Fruit found find lemon fruits found ifPresent f System out println f getName This other piece of code uses a lambda expression to provide a Supplier which can ultimately provide a default answer if the optional object is empty Optional Fruit found find lemon fruits Fruit fruit found orElseGet new Fruit Lemon Clearly we can see that these convenient methods simplify a lot having to work with the optional objects So What s Wrong with Optional The question we face is will Optional get rid of null references And the answer is an emphatic no So detractors immediately question its value asking then what is it good for that we couldn t do by other means already Unlike functional languages like SML o Haskell which never had the concept of null references in Java we cannot simply get rid of the null references that have historically existed This will continue to exist and they arguably have their proper uses just to mention an example three valued logic I doubt that the intention with the Optional class is to replace every single nullable reference but to help in the creation of more robust APIs in which just by reading the signature of a method we could tell if we can expect an optional value or not and force the programmer to use this value accordingly But ultimately Optional will be just another reference and subject to same weaknesses of every other reference in the language It is quite evident that Optional is not going to save the day How these optional objects are supposed to be used or whether they are valuable or not in Java has been the matter of a heated debate in the project lambda mailing list From the detractors we hear interesting arguments like The fact that other alternatives exist i e the Eclipse IDE supports a set of proprietary annotations for static analysis of nullability the JSR 305 with annotations like Nullable and NonNull Some would like it to be usable as in the functional world which is not entirely possible in Java since the language lacks many features existing in functional programming languages like SML or Haskell i e pattern matching Others argue about how it is impossible to retrofit preexisting code to use this idiom i e List get Object which will continue to return null And some complain about the fact that the lack of language support for optional values creates a potential scenario in which Optional could be used inconsistently in the APIs by this creating incompatibilities pretty much like the ones we will have with the rest of the Java API which cannot be retrofitted to use the new Optional class A compelling argument is that if the programmer invokes the get method in an optional object if it is empty it will raise a NoSuchElementException which is pretty much the same problem that we have with nulls just with a different exception So it would appear that the benefits of Optional are really questionable and are probably constrained to improving readability and enforcing public interface contracts Optional Objects in the Stream API Irrespective of the debate the optional objects are here to stay and they are already being used in the new Stream API in methods like findFirst findAny max and min It could be worth mentioning that a very similar class has been in used in the successful Guava Collections Framework For instance consider the following example where we extract from a stream the last fruit name in alphabetical order Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit max fruits max comparing Fruit getName if max isPresent String fruitName max get getName grape Or this another one in which we obtain the first fruit in a stream Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit first fruits findFirst if first isPresent String fruitName first get getName apple Ceylon Programming Language and Optional Types Recently I started to play a bit with the Ceylon programming language since I was doing a research for another post that I am planning to publish soon in this blog I must say I am not a big fan of Ceylon but still I found particularly interesting that in Ceylon this concept of optional values is taken a bit further and the language itself offers some syntactic sugar for this idiom In this language we can mark any type with a question mark in order to indicate that its type is an optional type For instance this find function would be very similar to our original Java version but this time returning an optional Fruit reference 1 Also notice that a null value is compatible with the optional Fruit reference 7 Fruit find String name List Fruit fruits for Fruit fruit in fruits if fruit name name return fruit return null And we could use it with this Ceylon code similar to our last Java snippet in which we used an optional value List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find lemon fruits print fruit else Fruit Kiwi name Notice the use of the else keyword here is pretty similar to the method orElse in the Java 8 Optional class Also notice that the syntax is similar to the declaration of C nullable types but it means something totally different in Ceylon It may be worth mentioning that Kotlin the programming language under development by Jetbrains has a similar feature related to null safety so maybe we are before a trend in programming languages An alternative way of doing this would have been like this List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find apple fruits if exists fruit String fruitName fruit name print The found fruit is fruitName else Notice the use of the exists keyword here 3 serves the same purpose as the isPresent method invocation in the Java Optional class The great advantage of Ceylon over Java is that they can use this optional type in the APIs since the beginning within the realm of their language they won t have to deal with incompatibilities and it can be fully supported everywhere perhaps their problem will be in their integration with the rest of the Java APIs but I have not studied this yet Hopefully in future releases of Java this same syntactic sugar from Ceylon and Kotlin will also be made available in the Java programming language perhaps using under the hood this new Optional class introduced in Java 8 Further Reading Java Language Specification The Billion Dollars Mistake Refactoring Catalog Ceylon Programming Language Kotlin Programming Language C Nullable Types Avoid Using Null Guava Framework More Discussion on Java s Optional Java Infinite Streams Java Streams API Preview Java Streams Preview vs Net High Order Programming with LINQ Share this Email Facebook Twitter Like this Like Loading Related April 10 2013 by Edwin Dalorzo Categories Java Programming Tags ceylon java null pointer programming sml 23 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Overview Of The Task Parallel Library TPL Memoized Fibonacci Numbers with Java 8 23 thoughts on Java 8 Optional Objects lukaseder says April 11 2013 at 3 15 pm Very nice research Well you know that blank and initial states were already known to Turing 1 You could also argue that the neutral or zero state were required in the Babbage Engine 2 which dates back to Ada of Lovelace in the 1800 s On the other hand mathematicians also prefer to distinguish nothing from the empty set 3 which is a set with nothing inside This compares well with NONE and SOME Anyway I ve given Java s Optional some thought I m really not sure if I m going to like it Since Java is so incredibly backwards compatible none of the existing APIs will be retrofitted to return Optional e g interface List Optional get int index So not only as you said can you assign null to an Optional variable but the absence of Optional doesn t guarantee the semantics of SOME When we mix the two ways of thinking we will wind up with two checks instead of one 1 from me to Java s solution unlike Ceylon 1 http en wikipedia org wiki Turing machine 2 http www fourmilab ch babbage sketch html 3 http en wikipedia org wiki Empty set Reply Edwin Dalorzo says April 11 2013 at 4 16 pm Great comment Lukas These are really good references and comparisons with other mathematical models It will take me some time to go over all these but I will certainly enjoy it You are totally right as long as the null reference exists there is no way that something like Optional will get rid of null dereferencing problem in certain cases like the one you mention with two null checks it could make it worse I still believe that in the case of return values it makes the APIs more explicit Perhaps we cannot retrofit the uncountable lines of code already using other mechanisms like the List example you gave but from this day on at least we have an alternative Like you I also think the Ceylon solution is kind of neat although ironically they did not get rid of null entirely I still have much to learn in this subject but the exercise of writing this article helped me a lot to understand this classical problem and your references will enriched the discussion Reply lukaseder says April 12 2013 at 7 14 am Hehe I actually wasn t 100 sure about Turing and Ada But I was sure those guys must ve suffered from NullTapeExceptions The only ones who probably didn t have this problem were the Romans who started counting at I II III IV V They couldn t model the absense of apples and pears on their markets Yeah Ceylon cannot get rid of null easily if they want to be interoperable with Java Although there seem to be ways as this interesting article displays claiming to be able to get rid of Java s null in Scala http dysphoria net scala sip nulls xhtml Nick G NicolasGuzCa says April 14 2013 at 8 43 pm Great Article Using Optional Objects will definitely improve Java development I had one of those problems you mentioned and went days trying to figure what was wrong In the end I programmed a series of try catch to help me with the nulls but it s not the most optimal solution Reply DvH says April 15 2013 at 7 19 am IMO the Optional class is just additional baggage I immediately think of those creative folks who find good reasons to return Optional sometimes and null at other times I d prefer and use the Nullable annotation Reply Edwin Dalorzo says April 15 2013 at 5 43 pm Like it or not the new Optional class will be part of the JDK 8 Stream APIs so getting some familiarity with it and its purpose could be valuable even if you intend to use other alternatives in your own APIs Also as it gets more popular chances are that APIs created by other developers using JDK 8 or later version will contain this new class and you would still be forced to use it even when you wouldn t expose it in your own APIs Reply Jack Wright says April 15 2013 at 1 33 pm It s nice to see java is finally getting the maybe monad http en wikipedia org wiki Monad functional programming The Maybe monad I believe from a traditional OO background it is hard at first glance to understand why this is really useful I personally would like to see more monads like this in java much like they already exist in scala It is true that Optional value could be null though I would say by the very contract of saying something is contained in optional that it should be unnecessary to add any other declarations as they would be redundant Scala does provide some useful Syntactic sugar for dealing with results that might be null and wrapping them in option ie Option apply will check for null and return None As far as syntactic sugar goes what I would really prefer to see is something like scala s for comprehension or

    Original URL path: http://blog.informatech.cr/2013/04/10/java-optional-objects/?replytocom=1390 (2015-08-19)
    Open archived version from archive

  • Java 8 Optional Objects | Informatech CR Blog
    of a As you can see option is a data type with two constructors one of them stores nothing i e NONE whereas the other is capable of storing a polymorphic value of some value type a where a is just a placeholder for the actual type Under this model the piece of code we wrote before in Java to find a fruit by its name could be rewritten in SML as follows fun find name fruits case fruits of NONE Fruit s fs if s name then SOME Fruit s else find name fs There are several ways to achieve this in SML this example just shows one way to do it The important point here is that there is no such thing as null instead a value NONE is returned when nothing is found 3 and a value SOME fruit is returned otherwise 5 When a programmer uses this find method he knows that it returns an option type value and therefore the programmer is forced to check the nature of the value obtained to see if it is either NONE 6 or SOME fruit 7 somewhat like this let val fruits Fruit apple Fruit grape Fruit orange val found find grape fruits in case found of NONE print Nothing found SOME Fruit f print Found fruit f end Having to check for the true nature of the returned option makes it impossible to misinterpret the result Java Optional Types It s a joy that finally in Java 8 we ll have a new class called Optional that allows us to implement a similar idiom as that from the functional world As in the case of of SML the Optional type is polymorphic and may contain a value or be empty So we could rewrite our previous code snippet as follows public static Optional Fruit find String name List Fruit fruits for Fruit fruit fruits if fruit getName equals name return Optional of fruit return Optional empty As you can see the method now returns an Optional reference 1 if something is found the Optional object is constructed with a value 4 otherwise is constructed empty 7 And the programmer using this code would do something as follows List Fruit fruits asList new Fruit apple new Fruit grape new Fruit orange Optional Fruit found find lemon fruits if found isPresent Fruit fruit found get String name fruit getName Now it is made evident in the type of the find method that it returns an optional value 5 and the user of this method has to program his code accordingly 6 7 So we see that the adoption of this functional idiom is likely to make our code safer less prompt to null dereferencing problems and as a result more robust and less error prone Of course it is not a perfect solution because after all Optional references can also be erroneously set to null references but I would expect that programmers stick to the convention of not passing null references where an optional object is expected pretty much as we today consider a good practice not to pass a null reference where a collection or an array is expected in these cases the correct is to pass an empty array or collection The point here is that now we have a mechanism in the API that we can use to make explicit that for a given reference we may not have a value to assign it and the user is forced by the API to verify that Quoting an article I reference later about the use of optional objects in the Guava Collections framework Besides the increase in readability that comes from giving null a name the biggest advantage of Optional is its idiot proof ness It forces you to actively think about the absent case if you want your program to compile at all since you have to actively unwrap the Optional and address that case Other Convenient Methods As of the today besides the static methods of and empty explained above the Optional class contains the following convenient instance methods ifPresent Which returns true if a value is present in the optional get Which returns a reference to the item contained in the optional object if present otherwise throws a NoSuchElementException ifPresent Consumer T consumer Which passess the optional value if present to the provided Consumer which could be implemented through a lambda expression or method reference orElse T other Which returns the value if present otherwise returns the value in other orElseGet Supplier T other Which returns the value if present otherwise returns the value provided by the Supplier which could be implemented with a lambda expression or method reference orElseThrow Supplier T exceptionSupplier Which returns the value if present otherwise throws the exception provided by the Supplier which could be implemented with a lambda expression or method reference Avoiding Boilerplate Presence Checks We can use some of the convenient methods mentioned above to avoid the need of having to check if a value is present in the optional object For instance we may want to use a default fruit value if nothing is found let s say that we would like to use a Kiwi So we could rewrite our previous code like this Optional Fruit found find lemon fruits String name found orElse new Fruit Kiwi getName In this other example the code prints the fruit name to the main output if the fruit is present In this case we implement the Consumer with a lambda expression Optional Fruit found find lemon fruits found ifPresent f System out println f getName This other piece of code uses a lambda expression to provide a Supplier which can ultimately provide a default answer if the optional object is empty Optional Fruit found find lemon fruits Fruit fruit found orElseGet new Fruit Lemon Clearly we can see that these convenient methods simplify a lot having to work with the optional objects So What s Wrong with Optional The question we face is will Optional get rid of null references And the answer is an emphatic no So detractors immediately question its value asking then what is it good for that we couldn t do by other means already Unlike functional languages like SML o Haskell which never had the concept of null references in Java we cannot simply get rid of the null references that have historically existed This will continue to exist and they arguably have their proper uses just to mention an example three valued logic I doubt that the intention with the Optional class is to replace every single nullable reference but to help in the creation of more robust APIs in which just by reading the signature of a method we could tell if we can expect an optional value or not and force the programmer to use this value accordingly But ultimately Optional will be just another reference and subject to same weaknesses of every other reference in the language It is quite evident that Optional is not going to save the day How these optional objects are supposed to be used or whether they are valuable or not in Java has been the matter of a heated debate in the project lambda mailing list From the detractors we hear interesting arguments like The fact that other alternatives exist i e the Eclipse IDE supports a set of proprietary annotations for static analysis of nullability the JSR 305 with annotations like Nullable and NonNull Some would like it to be usable as in the functional world which is not entirely possible in Java since the language lacks many features existing in functional programming languages like SML or Haskell i e pattern matching Others argue about how it is impossible to retrofit preexisting code to use this idiom i e List get Object which will continue to return null And some complain about the fact that the lack of language support for optional values creates a potential scenario in which Optional could be used inconsistently in the APIs by this creating incompatibilities pretty much like the ones we will have with the rest of the Java API which cannot be retrofitted to use the new Optional class A compelling argument is that if the programmer invokes the get method in an optional object if it is empty it will raise a NoSuchElementException which is pretty much the same problem that we have with nulls just with a different exception So it would appear that the benefits of Optional are really questionable and are probably constrained to improving readability and enforcing public interface contracts Optional Objects in the Stream API Irrespective of the debate the optional objects are here to stay and they are already being used in the new Stream API in methods like findFirst findAny max and min It could be worth mentioning that a very similar class has been in used in the successful Guava Collections Framework For instance consider the following example where we extract from a stream the last fruit name in alphabetical order Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit max fruits max comparing Fruit getName if max isPresent String fruitName max get getName grape Or this another one in which we obtain the first fruit in a stream Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit first fruits findFirst if first isPresent String fruitName first get getName apple Ceylon Programming Language and Optional Types Recently I started to play a bit with the Ceylon programming language since I was doing a research for another post that I am planning to publish soon in this blog I must say I am not a big fan of Ceylon but still I found particularly interesting that in Ceylon this concept of optional values is taken a bit further and the language itself offers some syntactic sugar for this idiom In this language we can mark any type with a question mark in order to indicate that its type is an optional type For instance this find function would be very similar to our original Java version but this time returning an optional Fruit reference 1 Also notice that a null value is compatible with the optional Fruit reference 7 Fruit find String name List Fruit fruits for Fruit fruit in fruits if fruit name name return fruit return null And we could use it with this Ceylon code similar to our last Java snippet in which we used an optional value List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find lemon fruits print fruit else Fruit Kiwi name Notice the use of the else keyword here is pretty similar to the method orElse in the Java 8 Optional class Also notice that the syntax is similar to the declaration of C nullable types but it means something totally different in Ceylon It may be worth mentioning that Kotlin the programming language under development by Jetbrains has a similar feature related to null safety so maybe we are before a trend in programming languages An alternative way of doing this would have been like this List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find apple fruits if exists fruit String fruitName fruit name print The found fruit is fruitName else Notice the use of the exists keyword here 3 serves the same purpose as the isPresent method invocation in the Java Optional class The great advantage of Ceylon over Java is that they can use this optional type in the APIs since the beginning within the realm of their language they won t have to deal with incompatibilities and it can be fully supported everywhere perhaps their problem will be in their integration with the rest of the Java APIs but I have not studied this yet Hopefully in future releases of Java this same syntactic sugar from Ceylon and Kotlin will also be made available in the Java programming language perhaps using under the hood this new Optional class introduced in Java 8 Further Reading Java Language Specification The Billion Dollars Mistake Refactoring Catalog Ceylon Programming Language Kotlin Programming Language C Nullable Types Avoid Using Null Guava Framework More Discussion on Java s Optional Java Infinite Streams Java Streams API Preview Java Streams Preview vs Net High Order Programming with LINQ Share this Email Facebook Twitter Like this Like Loading Related April 10 2013 by Edwin Dalorzo Categories Java Programming Tags ceylon java null pointer programming sml 23 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Overview Of The Task Parallel Library TPL Memoized Fibonacci Numbers with Java 8 23 thoughts on Java 8 Optional Objects lukaseder says April 11 2013 at 3 15 pm Very nice research Well you know that blank and initial states were already known to Turing 1 You could also argue that the neutral or zero state were required in the Babbage Engine 2 which dates back to Ada of Lovelace in the 1800 s On the other hand mathematicians also prefer to distinguish nothing from the empty set 3 which is a set with nothing inside This compares well with NONE and SOME Anyway I ve given Java s Optional some thought I m really not sure if I m going to like it Since Java is so incredibly backwards compatible none of the existing APIs will be retrofitted to return Optional e g interface List Optional get int index So not only as you said can you assign null to an Optional variable but the absence of Optional doesn t guarantee the semantics of SOME When we mix the two ways of thinking we will wind up with two checks instead of one 1 from me to Java s solution unlike Ceylon 1 http en wikipedia org wiki Turing machine 2 http www fourmilab ch babbage sketch html 3 http en wikipedia org wiki Empty set Reply Edwin Dalorzo says April 11 2013 at 4 16 pm Great comment Lukas These are really good references and comparisons with other mathematical models It will take me some time to go over all these but I will certainly enjoy it You are totally right as long as the null reference exists there is no way that something like Optional will get rid of null dereferencing problem in certain cases like the one you mention with two null checks it could make it worse I still believe that in the case of return values it makes the APIs more explicit Perhaps we cannot retrofit the uncountable lines of code already using other mechanisms like the List example you gave but from this day on at least we have an alternative Like you I also think the Ceylon solution is kind of neat although ironically they did not get rid of null entirely I still have much to learn in this subject but the exercise of writing this article helped me a lot to understand this classical problem and your references will enriched the discussion Reply lukaseder says April 12 2013 at 7 14 am Hehe I actually wasn t 100 sure about Turing and Ada But I was sure those guys must ve suffered from NullTapeExceptions The only ones who probably didn t have this problem were the Romans who started counting at I II III IV V They couldn t model the absense of apples and pears on their markets Yeah Ceylon cannot get rid of null easily if they want to be interoperable with Java Although there seem to be ways as this interesting article displays claiming to be able to get rid of Java s null in Scala http dysphoria net scala sip nulls xhtml Nick G NicolasGuzCa says April 14 2013 at 8 43 pm Great Article Using Optional Objects will definitely improve Java development I had one of those problems you mentioned and went days trying to figure what was wrong In the end I programmed a series of try catch to help me with the nulls but it s not the most optimal solution Reply DvH says April 15 2013 at 7 19 am IMO the Optional class is just additional baggage I immediately think of those creative folks who find good reasons to return Optional sometimes and null at other times I d prefer and use the Nullable annotation Reply Edwin Dalorzo says April 15 2013 at 5 43 pm Like it or not the new Optional class will be part of the JDK 8 Stream APIs so getting some familiarity with it and its purpose could be valuable even if you intend to use other alternatives in your own APIs Also as it gets more popular chances are that APIs created by other developers using JDK 8 or later version will contain this new class and you would still be forced to use it even when you wouldn t expose it in your own APIs Reply Jack Wright says April 15 2013 at 1 33 pm It s nice to see java is finally getting the maybe monad http en wikipedia org wiki Monad functional programming The Maybe monad I believe from a traditional OO background it is hard at first glance to understand why this is really useful I personally would like to see more monads like this in java much like they already exist in scala It is true that Optional value could be null though I would say by the very contract of saying something is contained in optional that it should be unnecessary to add any other declarations as they would be redundant Scala does provide some useful Syntactic sugar for dealing with results that might be null and wrapping them in option ie Option apply will check for null and return None As far as syntactic sugar goes what I would really prefer to see is something like scala

    Original URL path: http://blog.informatech.cr/2013/04/10/java-optional-objects/?replytocom=1400 (2015-08-19)
    Open archived version from archive

  • Java 8 Optional Objects | Informatech CR Blog
    a As you can see option is a data type with two constructors one of them stores nothing i e NONE whereas the other is capable of storing a polymorphic value of some value type a where a is just a placeholder for the actual type Under this model the piece of code we wrote before in Java to find a fruit by its name could be rewritten in SML as follows fun find name fruits case fruits of NONE Fruit s fs if s name then SOME Fruit s else find name fs There are several ways to achieve this in SML this example just shows one way to do it The important point here is that there is no such thing as null instead a value NONE is returned when nothing is found 3 and a value SOME fruit is returned otherwise 5 When a programmer uses this find method he knows that it returns an option type value and therefore the programmer is forced to check the nature of the value obtained to see if it is either NONE 6 or SOME fruit 7 somewhat like this let val fruits Fruit apple Fruit grape Fruit orange val found find grape fruits in case found of NONE print Nothing found SOME Fruit f print Found fruit f end Having to check for the true nature of the returned option makes it impossible to misinterpret the result Java Optional Types It s a joy that finally in Java 8 we ll have a new class called Optional that allows us to implement a similar idiom as that from the functional world As in the case of of SML the Optional type is polymorphic and may contain a value or be empty So we could rewrite our previous code snippet as follows public static Optional Fruit find String name List Fruit fruits for Fruit fruit fruits if fruit getName equals name return Optional of fruit return Optional empty As you can see the method now returns an Optional reference 1 if something is found the Optional object is constructed with a value 4 otherwise is constructed empty 7 And the programmer using this code would do something as follows List Fruit fruits asList new Fruit apple new Fruit grape new Fruit orange Optional Fruit found find lemon fruits if found isPresent Fruit fruit found get String name fruit getName Now it is made evident in the type of the find method that it returns an optional value 5 and the user of this method has to program his code accordingly 6 7 So we see that the adoption of this functional idiom is likely to make our code safer less prompt to null dereferencing problems and as a result more robust and less error prone Of course it is not a perfect solution because after all Optional references can also be erroneously set to null references but I would expect that programmers stick to the convention of not passing null references where an optional object is expected pretty much as we today consider a good practice not to pass a null reference where a collection or an array is expected in these cases the correct is to pass an empty array or collection The point here is that now we have a mechanism in the API that we can use to make explicit that for a given reference we may not have a value to assign it and the user is forced by the API to verify that Quoting an article I reference later about the use of optional objects in the Guava Collections framework Besides the increase in readability that comes from giving null a name the biggest advantage of Optional is its idiot proof ness It forces you to actively think about the absent case if you want your program to compile at all since you have to actively unwrap the Optional and address that case Other Convenient Methods As of the today besides the static methods of and empty explained above the Optional class contains the following convenient instance methods ifPresent Which returns true if a value is present in the optional get Which returns a reference to the item contained in the optional object if present otherwise throws a NoSuchElementException ifPresent Consumer T consumer Which passess the optional value if present to the provided Consumer which could be implemented through a lambda expression or method reference orElse T other Which returns the value if present otherwise returns the value in other orElseGet Supplier T other Which returns the value if present otherwise returns the value provided by the Supplier which could be implemented with a lambda expression or method reference orElseThrow Supplier T exceptionSupplier Which returns the value if present otherwise throws the exception provided by the Supplier which could be implemented with a lambda expression or method reference Avoiding Boilerplate Presence Checks We can use some of the convenient methods mentioned above to avoid the need of having to check if a value is present in the optional object For instance we may want to use a default fruit value if nothing is found let s say that we would like to use a Kiwi So we could rewrite our previous code like this Optional Fruit found find lemon fruits String name found orElse new Fruit Kiwi getName In this other example the code prints the fruit name to the main output if the fruit is present In this case we implement the Consumer with a lambda expression Optional Fruit found find lemon fruits found ifPresent f System out println f getName This other piece of code uses a lambda expression to provide a Supplier which can ultimately provide a default answer if the optional object is empty Optional Fruit found find lemon fruits Fruit fruit found orElseGet new Fruit Lemon Clearly we can see that these convenient methods simplify a lot having to work with the optional objects So What s Wrong with Optional The question we face is will Optional get rid of null references And the answer is an emphatic no So detractors immediately question its value asking then what is it good for that we couldn t do by other means already Unlike functional languages like SML o Haskell which never had the concept of null references in Java we cannot simply get rid of the null references that have historically existed This will continue to exist and they arguably have their proper uses just to mention an example three valued logic I doubt that the intention with the Optional class is to replace every single nullable reference but to help in the creation of more robust APIs in which just by reading the signature of a method we could tell if we can expect an optional value or not and force the programmer to use this value accordingly But ultimately Optional will be just another reference and subject to same weaknesses of every other reference in the language It is quite evident that Optional is not going to save the day How these optional objects are supposed to be used or whether they are valuable or not in Java has been the matter of a heated debate in the project lambda mailing list From the detractors we hear interesting arguments like The fact that other alternatives exist i e the Eclipse IDE supports a set of proprietary annotations for static analysis of nullability the JSR 305 with annotations like Nullable and NonNull Some would like it to be usable as in the functional world which is not entirely possible in Java since the language lacks many features existing in functional programming languages like SML or Haskell i e pattern matching Others argue about how it is impossible to retrofit preexisting code to use this idiom i e List get Object which will continue to return null And some complain about the fact that the lack of language support for optional values creates a potential scenario in which Optional could be used inconsistently in the APIs by this creating incompatibilities pretty much like the ones we will have with the rest of the Java API which cannot be retrofitted to use the new Optional class A compelling argument is that if the programmer invokes the get method in an optional object if it is empty it will raise a NoSuchElementException which is pretty much the same problem that we have with nulls just with a different exception So it would appear that the benefits of Optional are really questionable and are probably constrained to improving readability and enforcing public interface contracts Optional Objects in the Stream API Irrespective of the debate the optional objects are here to stay and they are already being used in the new Stream API in methods like findFirst findAny max and min It could be worth mentioning that a very similar class has been in used in the successful Guava Collections Framework For instance consider the following example where we extract from a stream the last fruit name in alphabetical order Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit max fruits max comparing Fruit getName if max isPresent String fruitName max get getName grape Or this another one in which we obtain the first fruit in a stream Stream Fruit fruits asList new Fruit apple new Fruit grape stream Optional Fruit first fruits findFirst if first isPresent String fruitName first get getName apple Ceylon Programming Language and Optional Types Recently I started to play a bit with the Ceylon programming language since I was doing a research for another post that I am planning to publish soon in this blog I must say I am not a big fan of Ceylon but still I found particularly interesting that in Ceylon this concept of optional values is taken a bit further and the language itself offers some syntactic sugar for this idiom In this language we can mark any type with a question mark in order to indicate that its type is an optional type For instance this find function would be very similar to our original Java version but this time returning an optional Fruit reference 1 Also notice that a null value is compatible with the optional Fruit reference 7 Fruit find String name List Fruit fruits for Fruit fruit in fruits if fruit name name return fruit return null And we could use it with this Ceylon code similar to our last Java snippet in which we used an optional value List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find lemon fruits print fruit else Fruit Kiwi name Notice the use of the else keyword here is pretty similar to the method orElse in the Java 8 Optional class Also notice that the syntax is similar to the declaration of C nullable types but it means something totally different in Ceylon It may be worth mentioning that Kotlin the programming language under development by Jetbrains has a similar feature related to null safety so maybe we are before a trend in programming languages An alternative way of doing this would have been like this List Fruit fruits Fruit apple Fruit grape Fruit orange Fruit fruit find apple fruits if exists fruit String fruitName fruit name print The found fruit is fruitName else Notice the use of the exists keyword here 3 serves the same purpose as the isPresent method invocation in the Java Optional class The great advantage of Ceylon over Java is that they can use this optional type in the APIs since the beginning within the realm of their language they won t have to deal with incompatibilities and it can be fully supported everywhere perhaps their problem will be in their integration with the rest of the Java APIs but I have not studied this yet Hopefully in future releases of Java this same syntactic sugar from Ceylon and Kotlin will also be made available in the Java programming language perhaps using under the hood this new Optional class introduced in Java 8 Further Reading Java Language Specification The Billion Dollars Mistake Refactoring Catalog Ceylon Programming Language Kotlin Programming Language C Nullable Types Avoid Using Null Guava Framework More Discussion on Java s Optional Java Infinite Streams Java Streams API Preview Java Streams Preview vs Net High Order Programming with LINQ Share this Email Facebook Twitter Like this Like Loading Related April 10 2013 by Edwin Dalorzo Categories Java Programming Tags ceylon java null pointer programming sml 23 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Overview Of The Task Parallel Library TPL Memoized Fibonacci Numbers with Java 8 23 thoughts on Java 8 Optional Objects lukaseder says April 11 2013 at 3 15 pm Very nice research Well you know that blank and initial states were already known to Turing 1 You could also argue that the neutral or zero state were required in the Babbage Engine 2 which dates back to Ada of Lovelace in the 1800 s On the other hand mathematicians also prefer to distinguish nothing from the empty set 3 which is a set with nothing inside This compares well with NONE and SOME Anyway I ve given Java s Optional some thought I m really not sure if I m going to like it Since Java is so incredibly backwards compatible none of the existing APIs will be retrofitted to return Optional e g interface List Optional get int index So not only as you said can you assign null to an Optional variable but the absence of Optional doesn t guarantee the semantics of SOME When we mix the two ways of thinking we will wind up with two checks instead of one 1 from me to Java s solution unlike Ceylon 1 http en wikipedia org wiki Turing machine 2 http www fourmilab ch babbage sketch html 3 http en wikipedia org wiki Empty set Reply Edwin Dalorzo says April 11 2013 at 4 16 pm Great comment Lukas These are really good references and comparisons with other mathematical models It will take me some time to go over all these but I will certainly enjoy it You are totally right as long as the null reference exists there is no way that something like Optional will get rid of null dereferencing problem in certain cases like the one you mention with two null checks it could make it worse I still believe that in the case of return values it makes the APIs more explicit Perhaps we cannot retrofit the uncountable lines of code already using other mechanisms like the List example you gave but from this day on at least we have an alternative Like you I also think the Ceylon solution is kind of neat although ironically they did not get rid of null entirely I still have much to learn in this subject but the exercise of writing this article helped me a lot to understand this classical problem and your references will enriched the discussion Reply lukaseder says April 12 2013 at 7 14 am Hehe I actually wasn t 100 sure about Turing and Ada But I was sure those guys must ve suffered from NullTapeExceptions The only ones who probably didn t have this problem were the Romans who started counting at I II III IV V They couldn t model the absense of apples and pears on their markets Yeah Ceylon cannot get rid of null easily if they want to be interoperable with Java Although there seem to be ways as this interesting article displays claiming to be able to get rid of Java s null in Scala http dysphoria net scala sip nulls xhtml Nick G NicolasGuzCa says April 14 2013 at 8 43 pm Great Article Using Optional Objects will definitely improve Java development I had one of those problems you mentioned and went days trying to figure what was wrong In the end I programmed a series of try catch to help me with the nulls but it s not the most optimal solution Reply DvH says April 15 2013 at 7 19 am IMO the Optional class is just additional baggage I immediately think of those creative folks who find good reasons to return Optional sometimes and null at other times I d prefer and use the Nullable annotation Reply Edwin Dalorzo says April 15 2013 at 5 43 pm Like it or not the new Optional class will be part of the JDK 8 Stream APIs so getting some familiarity with it and its purpose could be valuable even if you intend to use other alternatives in your own APIs Also as it gets more popular chances are that APIs created by other developers using JDK 8 or later version will contain this new class and you would still be forced to use it even when you wouldn t expose it in your own APIs Reply Jack Wright says April 15 2013 at 1 33 pm It s nice to see java is finally getting the maybe monad http en wikipedia org wiki Monad functional programming The Maybe monad I believe from a traditional OO background it is hard at first glance to understand why this is really useful I personally would like to see more monads like this in java much like they already exist in scala It is true that Optional value could be null though I would say by the very contract of saying something is contained in optional that it should be unnecessary to add any other declarations as they would be redundant Scala does provide some useful Syntactic sugar for dealing with results that might be null and wrapping them in option ie Option apply will check for null and return None As far as syntactic sugar goes what I would really prefer to see is something like scala s

    Original URL path: http://blog.informatech.cr/2013/04/10/java-optional-objects/?replytocom=1408 (2015-08-19)
    Open archived version from archive