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".
  • Java Infinite Streams | Informatech CR Blog
    here That is why I left a comment in the tail method above saying triggers closure evaluation So we can see how the closure here is helping us to implement the lazy evaluation feature of the stream by delaying the time when the new stream cell is created Now our stream created by the from method above is infinite conceptually speaking Therefore if we try to evaluate it we could loop forever if it weren t because of the limitations in memory resources or the fact that integers in Java are bound to 31 bits 1 bit is reserved for the sign and that they wrap around when an overflow occurs A Finite Stream Based on a Predicate Now the question is how can we possibly extract values from this stream The problem is that if we try to extract anything from an infinite stream in any kind of loop we could go forever So what we need is a way to limit the number of elements in the stream to a discrete amount One way to do this is to create another stream but this time a finite stream based on the first one and that it only contains a discrete amount of elements from the infinite stream We could define the number of elements that we want based on a predicate And this is quite appropriate because one of the new functional interfaces in Java 8 is precisely Predicate Even better now that Java has extension methods and now that interfaces support the definition of static methods we could define the following methods in the stream interface itself public interface Stream T public default Stream T takeWhile Predicate super T return takeWhile this predicate public static T Stream T takeWhile Stream extends T source Predicate super T predicate if source isEmpty predicate test source head return new Empty creates new cons cell and a closure for the rest return new Cons source head takeWhile source tail predicate Now I have to admit that I defined these methods here because I thought it would be a good way to demonstrate these new features in Java 8 but I have not pondered the implications of my design That been said I also believe that having defined these methods directly in the interface avoids the need to define an implementation for them in the Empty and Cons classes themselves since they can consume this default implementation by inheritance Notice how the method takeWhile creates a new stream but as you can see in the moment that one of the stream nodes does not satisfy the predicate we return an empty stream node so this indicates the end of the stream and the end of the evaluation of the infinite stream By this we can generate a finite stream out of our infinite stream using a predicate to restrict the number of items we want to get out of the infinite stream We could do something like the following to obtain a new stream containing only the first 10 natural numbers Stream Integer tenNats from 0 takeWhile n n 10 Consuming the Stream In the next step what we would like to do is to provide a way to print the contents of a finite stream or do any other kind of tasks with the values in it i e serialize them send them over network etc Once again using Java 8 extension methods we can add a forEach method to the stream interface so that we can provide a Consumer to do something with the values within the stream The Consumer functional interface is also one of those new interfaces in the JDK 8 public interface Stream T public default void forEach Consumer super T consumer forEach this consumer public static T void forEach Stream extends T source Consumer super T consumer while source isEmpty consumer accept source head triggers closure evaluation source source tail Here you can see how we take advantage of the fact that empty stream cells return true for their method isEmpty Now if we would like to print those first 10 natural numbers we could do something as follows from 0 takeWhile n n 10 forEach System out println That is from an infinite stream of natural numbers take the first 10 natural numbers as a finite stream and consume those numbers by printing them to the main output Filtering Elements Another useful method could be one that filters elements out of a stream based on a predicate So let s add now a filter method This will be different from takeWhile in the sense that takeWhile takes elements out of a stream as long as a predicate is true whereas filter will take out all elements of a stream that satisfy a predicate which does not necessarily mean eagerly as you could infer from our use of closures here again public interface Stream T public default Stream T filter Predicate super T predicate return filter this predicate public static T Stream T filter Stream extends T source Predicate super T predicate if source isEmpty return new Empty if predicate test source head return new Cons source head filter source tail predicate return filter source tail predicate A weakness in this approach is the possibility of hitting a StackoverlflowError in the last line but leaving that aside you can see that we iterate over the original stream until we find a element that satisfies the predicate and then extract it and generate a closure capable of looking for the next one when that is necessary So once again we are taking advantage of lazy evaluation here Now we could do cool things like printing the first odd numbers in the range of 0 9 from our infinite stream like so from 0 takeWhile n n 10 filter n n 2 0 forEach System out println Evidently conceptually speaking we could work with any number of elements here not just 10 because our stream is infinite and

    Original URL path: http://blog.informatech.cr/2013/03/11/java-infinite-streams/ (2015-08-19)
    Open archived version from archive


  • Java Streams API Preview | Informatech CR Blog
    mostBought isPresent System out println mostBought get Related Posts Java Streams Preview vs Net High Order Programming with LINQ Java Infinite Streams Futher Reading JDK 8 Early Access Project Lambda JEP 107 Bulk Data Operations for Collections Where is the Java Collections Framework Going Share this Email Facebook Twitter Like this Like Loading Related March 25 2013 by Edwin Dalorzo Categories Java Programming Tags jdk8 lambda programming streams 16 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Java Streams Preview vs Net High Order Programming with LINQ Review of Programming Languages Course from Coursera 16 thoughts on Java Streams API Preview Pingback Java Streams Preview vs Net LINQ Informatech CR Blog Pingback Java Infinite Streams Informatech CR Blog Maurice Naftalin says March 29 2013 at 4 12 am There s a problem with the solution to No 3 if you have more than one equally youngest buyers the addition to TreeMap won t work the way you expect key equality for a TreeMap is defined by the compare or compareTo method so you get a list of sales for all the equally youngest buyers You can fix this by including extra sort keys in the Comparator byAge to resolve ties between equally youngest buyers assuming you ve done that there is a slightly neater solution than yours available byYoungest sales collect groupingBy Sale getBuyer new TreeMap byAge values stream findFirst An alternative fix is not to use TreeMap byYoungest sales collect groupingBy Sale getBuyer entrySet stream sorted comparing Entry Person List e e getKey getAge map Entry getValue findFirst Reply Edwin Dalorzo says March 29 2013 at 11 08 am Thanks for your comments Maurice This is great I will try to update the article with all your recommendations Man I ve got to tell you I just can t believe you dropped by my blog You just made my day Reply mauricen says March 29 2013 at 11 50 am You re welcome I enjoyed reading your post and working through the examples mauricen says March 29 2013 at 4 22 am There s a problem with No 3 if you have more than one equally youngest buyer Addition to a TreeMap is done using byAge compare as the key equality function so the sales of all the buyers of any age are added to the sales of the first buyer of that age You can fix this by adding extra sort keys to the Comparator byAge in which case there is a slightly neater solution than yours available byYoungest sales collect groupingBy Sale getBuyer new TreeMap byAge values stream findFirst or longer but clearer you can avoid using TreeMap altogether byYoungest sales collect groupingBy Sale getBuyer entrySet stream sorted comparing Entry Person List e e getKey getAge map Entry getValue findFirst The problem should probably be improved to specify exactly what behaviour is required when there is more than one equally youngest buyer Reply mauricen says March 29 2013 at 5 47

    Original URL path: http://blog.informatech.cr/2013/03/25/java-streams-api-preview/ (2015-08-19)
    Open archived version from archive

  • Java Streams Preview vs .Net High-Order Programming with LINQ | Informatech CR Blog
    stop there LINQ string moreNames Sam Samuel Dave Pascal Erik Sid var sNames moreNames TakeWhile c c StartsWith S Java Streams As of today there is no way to implement this idiom in Java using the streams API There is an alternative way to do this but it is not the same thing The beauty of takeWhile is that is should be short circuited that is it should stop the evaluation in the moment that one item does not satisfies the predicate The following version in Java does not have this property String names Sam Samuel Dave Pascal Erik Sid List String found found stream names collect partitioningBy c c startsWith S get true The collector created by partitioningBy line 4 forces the evaluation of the whole stream placing items into a boolean map where all items that satisfy the predicate are bound to true and all others to false So clearly it is not the same thing I hope that as the Oracle expert group works on the API they fix this omission Challenge 7 Skipping an Arbitrary Number of Items In this case we are interested in skipping items in a collection up to certain arbitrary number then we keep the rest of the items LINQ string vipNames Sam Samuel Samu Remo Arnold Terry var skippedList vipNames Skip 3 ToList Leaving the first 3 Java Streams In Java the solution consists in creating a new stream where the first n elements have been discarded As follows String vipNames Sam Samuel Samu Remo Arnold Terry List String skippedList skippedList stream vipNames substream 3 collect toList Challenge 8 Skipping Items Based on Predicate In this case we are interested in skipping items out of a collection as long as they satisfy a predicate Once we find an item that does not satisfy the predicate we take the rest of the items from there LINQ int numbers 1 2 3 4 5 6 7 8 9 10 11 12 20 var skippedList numbers SkipWhile c c 10 Java Streams With current streams API I found no way to implement this idiom Ordering Operators Challenge 9 Ordering Sorting Elements Order the elements of a collection alphabetically LINQ string friends Sam Pamela Dave Anders Erik friends friends OrderBy c c ToArray Java Streams In the case of Java we use the sorted method to produce the same result The sorted method can also accept a Comparator to determine the sorting criteria String friends Sam Pamela Dave Anders Erik friends stream friends sorted toArray String new Challenge 10 Ordering Sorting Elements by Specific Criterium Order the elements of a collection strings according to the length of the string LINQ string friends Sam Pamela Dave Anders Erik friends friends OrderBy c c Length ToArray Java Streams In this case we pass a Comparator to the sort method And once again we hit against the problem of overloaded methods defined in the API to deal with the lack of value types in Java Here we are forced to provide an explicit casting line 3 to help the compiler String friends Sam Pamela Dave Anders Erik friends stream friends sorted comparing ToIntFunction String String length toArray String new An alternative way could be to provide an implementation of the Comparator line 3 in this case by means of a binary lambda expression This is a little cleaner but more verbose String friends Sam Pamela Dave Anders Erik friends stream friends sorted s1 s2 Integer compare s1 length s2 length toArray String new Challenge 11 Ordering Sorting Elements by Multiple Criteria Order the elements of a collection of strings according to several sorting criteria LINQ string fruits grape passionfruit banana apple orange raspberry mango blueberry Sort the strings first by their length and then alphabetically preserving the first order var sortedFruits fruits OrderBy fruit fruit Length ThenBy fruit fruit Java Streams Originally I had thought it was not possible to implement this idiom with the latest release of the API but one of our readers had a good suggestion Even so I was not able to get rid of the castings in lines 5 and 7 Once again the interface pollution causes the need for castings to clarify which of the overloaded methods are the ones being implemented in Comparators and Comparator here String fruits grape passionfruit banana apple orange raspberry mango blueberry Comparator String comparator comparator comparing Function String Integer String length Integer compare thenComparing Comparator String String compareTo fruits stream fruits sorted comparator toArray String new Grouping Operators Challenge 12 Grouping by a Criterium Group the elements of a collection of strings by their length LINQ string names Sam Samuel Samu Ravi Ratna Barsha var groups names GroupBy c c Length Java Streams String names Sam Samuel Samu Ravi Ratna Barsha Map Integer List String groups groups stream names collect groupingBy String length Set Operators The current implementation of streams is way behind LINQ in this area From all possible set operations the only ones currently implemented are distinct and concat although concat is not a set operation because it would accept duplicates the correct would be to have a union operation but this does not exist in the stream API yet Challenge 13 Filter Distinct Elements Obtain all the distinct elements from a collection LINQ string songIds Song 1 Song 2 Song 2 Song 2 Song 3 Song 1 This will work as strings implement IComparable var uniqueSongIds songIds Distinct Java Streams String songIds Song 1 Song 2 Song 2 Song 2 Song 3 Song 1 according to Object equals stream songIds distinct Challenge 14 Union of Two Sets Join together two sets of items LINQ List string friends1 new List string Anders David James Jeff Joe Erik List string friends2 new List string Erik David Derik var allMyFriends friends1 Union friends2 Java Streams In Java we have to concatenate the two streams and then obtain the distinct elements List String friends1 asList Anders David James Jeff Joe Erik List String friends2 asList Erik David Derik Stream String allMyFriends concat friends1 stream friends2 stream distinct Element Operatos Challenge 15 First Element Obtain the first element of a collection LINQ string otherFriends Sam Danny Jeff Erik Anders Derik string firstName otherFriends First string firstNameConditional otherFriends First c c Length 5 Java Streams In Java we use the findFirst method which returns an Option object The object may contain something or nothing to validate that one must invoke the isPresent method on the returned object String otherFriends Sam Danny Jeff Erik Anders Derik Optional String found stream otherFriends findFirst Optional String maybe stream otherFriends filter c c length 5 findFirst if maybe isPresent do something with found data Range Operators Challenge 16 Generate a Range of Numbers Generate a range of numbers that are multiples of 11 LINQ var multiplesOfEleven Enumerable Range 1 100 Where c c 11 0 Java Streams IntStream multiplesOfEleven intRange 1 100 filter n n 11 0 Quantifier Operators Challenge 17 All Do all elements in a collection satisfy a predicate LINQ string persons Sam Danny Jeff Erik Anders Derik bool x persons All c c Length 5 Java Streams String persons Sam Danny Jeff Erik Anders Derik boolean x stream persons allMatch c c length 5 Challenge 18 Any Do any elements in a collection satisfy a predicate LINQ string persons Sam Danny Jeff Erik Anders Derik bool x persons Any c c Length 5 Java Streams String persons Sam Danny Jeff Erik Anders Derik boolean x stream persons anyMatch c c length 5 Merging Operators Challenge 19 Zip Combine two collections into a single collection LINQ string salutations Mr Mrs Ms Master string firstNames Samuel Jenny Joyace Sam string lastName McEnzie salutations Zip firstNames sal first sal first ToList ForEach c Console WriteLine c lastName Java Streams String salutations Mr Mrs Ms Master String firstNames Samuel Jenny Joyace Sam String lastName McEnzie zip stream salutations stream firstNames sal first sal first forEach c System out println c lastName In general things are still not looking good but I really hope that will change in the coming months There are challenges that will be difficult to overcome like the issues with value types but in my opinion we could live with those problems as long as we are provided with an API sufficiently expressive I am currently working on another set of examples in which I work on a small data model and see what I can do with it to run all kinds of queries using the Stream API but I will leave that for my next post Related Posts Java Streams API Preview Java Infinite Streams Further Reading JDK 8 Early Access Project Lambda JDK 8 Planned Features JEP 107 Bulk Data Operations for Collections Primitive Collections Support Breaks Existing Code Where is the Java Collections Framework Going Share this Email Facebook Twitter Like this Like Loading Related March 24 2013 by Edwin Dalorzo Categories Java Programming Tags java linq programming streams 40 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Improving Code With Fluent Interfaces Java Streams API Preview 40 thoughts on Java Streams Preview vs Net High Order Programming with LINQ Pingback Java Streams API Preview Informatech CR Blog Luis Aguilar says March 25 2013 at 10 32 am Wow Way to go Oracle The API looks great as far as I ve seen Of course there are some features missing but looks like is heading the right way One good thing about this is that now more C and functional developers will find appealing to work in Java and I think that s a great since it will widen its fan base Reply tkowalcz says March 26 2013 at 4 06 pm Hi It is a very nice comparison good job Some minor improvements are still possible E g Challenge 10 can be written as using current build b82 friends stream friends sorted Comparators comparing String length Integer compare toArray String new Then Challenge 11 is perfectly doable friends stream friends sorted Comparators comparing String length Integer compare thenComparing String compareTo toArray String new Reply Edwin Dalorzo says March 27 2013 at 9 05 am HI and thanks for dropping by and leaving your comments You are totally right I had not seen the thenComparing method in Comparator I will update the article with your solution This is great Reply spullara says March 26 2013 at 11 45 pm You can implement the predicate based skip limit but it isn t in the main library as they are difficult to support in the parallel stream case https github com spullara java future jdk8 blob master src main java spullara util Limiter java Reply Edwin Dalorzo says March 27 2013 at 9 11 am This is great thanks for sharing the link I have also experimented a bit with the implementation of this idioms using my own code I can see your point that it must be difficult to implement from the standpoint of the parallel APIs however I still think it needs to be added somehow to the API perhaps in the form of a collector This is a common high order function in most functional languages and not having it in the Java API would be a painful omission Don t you think Reply Pingback Java Infinite Streams Informatech CR Blog Mike Chaliy says March 27 2013 at 2 36 pm Why do you refer to extension methods for collections as LINQ This is quite misleading and can give false picture that Streams API is something similar to Language Integrated Queries Reply Edwin Dalorzo says March 27 2013 at 3 00 pm Thanks for dropping by and leave your comments As the article says the examples are based on the book Net 4 0 Generics under the chapter 4 LINQ to Objects So the author of the book Sudipta Mukherjee makes all these examples to demonstrate LINQ functionality It was never my intention to write an article on LINQ and all it can do but a comparison of what I could do with the Stream API if I wanted to implement similar idioms It is likely that your comment refers to my lack of a broader understanding of what LINQ actually means and it has to offer which wouldn t be surprise for me given the fact that I have little experience with LINQ itself That s why I based my comparisons in the examples provided by the book cited above Perhaps I may have misinterpreted the author in his use of all these examples to illustrate LINQ or perhaps the author only intended to illustrate just one aspect of this broad technology I based my article on this view to make a comparison Now you may also be referring to the point that there is no intention in making the stream API something comparable to LINQ which is true But still LINQ offers a good example of an API that makes extensive use of high order programming to query collections and even if the stream API is not yet intended to query things like XML or SQL I feel that it is still a good benchmark to compare the power of expressiveness in the API Wouldn t you agree Reply Anders Hybertz says March 28 2013 at 4 54 am I was wondering why you have the ToList on many of the C examples One of the nice features of LINQ is the lazy evaluation of the expressions Using ToList will actually materialize a new collection with the evaluated result Leaving out the ToList will only materialize the elements as they are iterated This provide a kind og infinitive collections where processing millions and millions of collection elements like rows from a database or lines from log files can be done with quite limited memory consumption It can also have quite positive performance significance If you have a collection list or db set and you will break out as soon as you find the first element that match a specified predicate then you only have to parse elements until the one found and not have to deal with the remaining elements in the collection Reply Luis Aguilar says March 28 2013 at 1 54 pm That s right Anders Actually that s what makes LINQ so powerful Lazy evaluation It is already noticeable how it improves processing times on collections but its true power is shown when it comes to database rows by using LINQ to SQL you can build up a SQL query the same you would query a collection and then execute it as soon as ToList is called letting LINQ to internally generate the best SQL query based in your expression and execute it at the database Reply Edwin Dalorzo says March 28 2013 at 10 09 pm Likewise in the case of Java streams the stream is not evaluated until a terminal operation is found As you well point out the collect method is a terminal operation I can only assume the method ToList is also a terminal operation in the LINQ example since it has to generate the list containing the items Reply LGnord says March 29 2013 at 9 29 am I am suprise but some of your challenge E g Ordering Sorting Elements by Specific Criterium How to you do when the stream is infinite May be it is a difference between java and linq Reply Edwin Dalorzo says March 29 2013 at 11 29 am You could not sort an infinite stream simply because it is infinite But you can transform an infinite stream into a finite stream For instance assuming that nats is a infinite stream of natural numbers you could do something like nats takeWhile n n 100 sort In this case the takeWhile method should allow us to transform the infinite stream of natural numbers into a finite stream containing a discrete number of elements in this case all those smaller than 100 That finite stream we could sort The basic problem with the API today is that we do not have a method takeWhile Reply jeckyl2010 says March 30 2013 at 4 29 am Adding more to the details of the LINQ have to say I m not at all familiar with the Java stream functionality but as most LINQ functions are utilizing the IEnumeable interface the NET extension methods allows one to extend the default set of LINQ operations with custom ones That is something when used with care really make code much more readable and a lot easier to maintain public static class Extension public static void Dump this IEnumerable self Predicate p foreach var element in self Where p p Console WriteLine element ToString Used in this way collection Dump p p Name Contains e Reply Edwin Dalorzo says March 30 2013 at 9 32 am That is true The power of extension methods here is that anyone at anytime can define new methods for an existing class In Java 8 we ll have something called default methods which will allow the designers of an interface to add default implementations to interface methods by this opening a door to evolve interfaces Although this feature is not the same as the extension methods from Net it has allowed the addition of a few new methods to preexisting collection interfaces One of those methods is the forEach method What you wrote in your comment can be achieved by doing collection stream filter p p getName contains e forEach System out println Or if I wanted to consume all items from a collection without filtering I could simply do collection forEach System out println So even when you cannot define new extension methods for the collection you may define as many new consumers as you want for instance collection forEach MyNetworkSocket send Reply Michael Bayne samskivert says March 30 2013 at 3 02 pm Here are the same challenges in Scala for comparison Reply Edwin Dalorzo says

    Original URL path: http://blog.informatech.cr/2013/03/24/java-streams-preview-vs-net-linq/ (2015-08-19)
    Open archived version from archive

  • ceylon | Informatech CR Blog
    interface of a Fruit Minimum and Maximum Another place where this could be potentially problematic is when reducing a collection to a value for instance to a maximum or minimum value Consider the following piece of code that can be used to determine which is the longest string in a collection public static String longest Collection String items if items isEmpty return null Iterator String iter items iterator String result iter next while iter hasNext String item iter next if item length result length result item return result In this case the question is what should be returned when the list provided is empty In this particular case a null value is returned once again opening the door for a potential null dereferencing problem The Functional World Strategy It s interesting that in the functional programming paradigm the statically typed programming languages evolved in a different direction In languages like SML or Haskell there is no such thing as a null value that causes exceptions when dereferenced These languages provide a special data type capable of holding an optional value and so it can be conveniently used to also express the possible absence of a value The following piece of code shows the definition of the SML option type datatype a option NONE SOME 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

    Original URL path: http://blog.informatech.cr/tag/ceylon/ (2015-08-19)
    Open archived version from archive

  • null pointer | Informatech CR Blog
    a Fruit Minimum and Maximum Another place where this could be potentially problematic is when reducing a collection to a value for instance to a maximum or minimum value Consider the following piece of code that can be used to determine which is the longest string in a collection public static String longest Collection String items if items isEmpty return null Iterator String iter items iterator String result iter next while iter hasNext String item iter next if item length result length result item return result In this case the question is what should be returned when the list provided is empty In this particular case a null value is returned once again opening the door for a potential null dereferencing problem The Functional World Strategy It s interesting that in the functional programming paradigm the statically typed programming languages evolved in a different direction In languages like SML or Haskell there is no such thing as a null value that causes exceptions when dereferenced These languages provide a special data type capable of holding an optional value and so it can be conveniently used to also express the possible absence of a value The following piece of code shows the definition of the SML option type datatype a option NONE SOME 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

    Original URL path: http://blog.informatech.cr/tag/null-pointer/ (2015-08-19)
    Open archived version from archive

  • sml | Informatech CR Blog
    a Fruit Minimum and Maximum Another place where this could be potentially problematic is when reducing a collection to a value for instance to a maximum or minimum value Consider the following piece of code that can be used to determine which is the longest string in a collection public static String longest Collection String items if items isEmpty return null Iterator String iter items iterator String result iter next while iter hasNext String item iter next if item length result length result item return result In this case the question is what should be returned when the list provided is empty In this particular case a null value is returned once again opening the door for a potential null dereferencing problem The Functional World Strategy It s interesting that in the functional programming paradigm the statically typed programming languages evolved in a different direction In languages like SML or Haskell there is no such thing as a null value that causes exceptions when dereferenced These languages provide a special data type capable of holding an optional value and so it can be conveniently used to also express the possible absence of a value The following piece of code shows the definition of the SML option type datatype a option NONE SOME 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

    Original URL path: http://blog.informatech.cr/tag/sml/ (2015-08-19)
    Open archived version from archive

  • JavaScript For Regular Guys (Part 1) | Informatech CR Blog
    Programming had to be on JavaScript by its first release So guys at ECMA had a dialogue at some point while writing the first language specification back in year 97 that goes a little something like this Dude 1 Dude JavaScript is cool so far and everything but everyone is using something called Object oriented something something Dude 2 Damn kids these days Let s just allow functions to contain variables and other functions Voilà We got classes Dude 1 That sounds like is going to confuse lots of people D Dude 2 Meh Not really Dude 1 But Dude 2 NOT REALLY I SAID Okay maybe it was not like that but since then we have like four or five different ways to define something like classes The one I like the most is as follows script type text javascript language text javascript function CarFactory var carsProduced 0 Private variable this name Car Factory Public variable this getCarsProduced new function Public getter return carsProduced this createCar function Public function showCarProductionMessage carsProduced function showCarProductionMessage Private function alert A car was produced var carFactory new CarFactory alert Factory name carFactory name carFactory createCar alert Cars produced so far carFactory getCarsProduced script How pretty does that looks So a function can also be a class definition with private members and all just like any object oriented language This is known as prototyping Hopefully the example is clear enough I have a couple of things to clarify though JavaScript while trying to be object oriented is still a scripted language never forget that So if you put the class definition after you use it you ll get a nice error complaining about the use of an undefined type since the interpreter has not yet seen the class prototype definition as it is after the code trying to use it Also look at the use of the keyword this Things are just starting to get more and more interesting for sure The this Keyword If you have worked with classes before surely you ll recognize the this keyword This magical keyword often refers to the class where the current method using it is defined Well in JavaScript once again screwing up with our brains the this keyword refers to the function owner and can refer to several things depending on the scope it is used Now you see how tightly coupled JavaScript is with the DOM tree The default owner for all scripts is the global window DOM element Now you can see the last two usages in the table involve the use of the call and apply functions These functions are useful if we would like to change the value this refers to That would be your homework Check the use of call and apply Conclusion So we have reviewed how JavaScript was conceived and how it is structured This is essential in order to understand more complex examples like DOM element events and asynchronous server calls and of course server side JavaScript

    Original URL path: http://blog.informatech.cr/2013/03/26/javascript-for-regular-guys-part-1/ (2015-08-19)
    Open archived version from archive

  • html | Informatech CR Blog
    can see the use of the setTimeout function JavaScript comes with a set of pre defined global functions that don t come from any object They just can be used anywhere No literally ANYWHERE If you come from a formal language like C or Java you know that at some point you ll need to include namespaces or packages so your code can use things defined somewhere else Yeah well with JavaScript this is not the case Global functions are auto magically imported by the browser itself In the case of the setTimeout function it takes two parameters the first is a function that will execute after a specified amount of milliseconds specified by the second parameter The function we specified as the first parameter is what we know as an anonymous function We call it anonymous because it has no name Really Yes really But you can assign a name to it if you want script type text javascript language text javascript function colorChanger var target document getElementById target target style color 00FF00 setTimeout colorChanger 2000 script It now has a name But we can still use it as a variable and pass it as first parameter of the setTimeout function Dammit JavaScript Anyways we slipped a little from the whole DOM topic The important thing you gotta remember is that the global document variable can be used to retrieve HTML elements by ID you already got the idea of what the DOM is all about After we have the element on a JavaScript variable we can change its attributes move it somewhere else on the tree or even just delete the crap out of it à la Godfather JavaScript Has No Class Even tough JavaScript is one of the most popular and used languages in the world is not anything close to any other language you might have seen before It is functional dynamic weakly typed and totally random at some points Is like taking all programming languages known to mankind and mash them together in one single surprise pack Seriously it gets a little crazy sometimes For instance even though it has weakly typed dynamic variables and other sorts of neat things it has no formal way of defining classes However as the languages evolved from old computers into 21st century a way to do something like Object oriented Programming had to be on JavaScript by its first release So guys at ECMA had a dialogue at some point while writing the first language specification back in year 97 that goes a little something like this Dude 1 Dude JavaScript is cool so far and everything but everyone is using something called Object oriented something something Dude 2 Damn kids these days Let s just allow functions to contain variables and other functions Voilà We got classes Dude 1 That sounds like is going to confuse lots of people D Dude 2 Meh Not really Dude 1 But Dude 2 NOT REALLY I SAID Okay maybe it

    Original URL path: http://blog.informatech.cr/tag/html/ (2015-08-19)
    Open archived version from archive