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".
  • development | Informatech CR Blog
    sexy code base This wiring will take place at the Main method of the application which will instantiate the repository class the View and the Presenter initialize everything and then finally run the application So here is our new Program class doing what it does best namespace Codenough Demos WinFormsMVP public static class Program STAThread public static void Main Application EnableVisualStyles Application SetCompatibleTextRenderingDefault false var clientsForm new ClientsForm var clientsRepository new ClientRepository var clientsPresenter new ClientsPresenter clientsForm clientsRepository clientsForm Closed Application Exit Application Run clientsForm If you smash on that Run toolbar button at this point you will see a really nice window poppin up on screen with the clients list box populated just like the old application only that this time all data coming back and forth the View is going through the Presenter what a controlling psycho freak Most important of it all You can now look in the code examples how each part has a single purpose The Model stores data the View displays data and the Presenter controls data flow Now the only thing left to do and hopefully show the real benefit behind this pattern is to try again and implement our pre defined unit tests so we can verify our application meets all requirements Meeting Acceptance Criteria Our application code has never been so ready before for some unit testing We had some already defined which we could not implement at the time simply because the code was being a total jack But now using the MVP pattern on all its glory we are set up for it So for unit testing I am using NUnit and Moq Moq is a library that allows me to create mocks in this case the repository class and the View interface without having to write additional code we don t like to do that Before we proceed let s see what a mock is and what it can do for us A mock is a fake implementation of an interface or a class which members produce data we already know basically is like making a TV display a TiVO recording instead of an actual live show You know in this example we can know what the data coming from the repository class is just by looking at the code but in the real world we might not have that source code at hand Or even worst that data might come from a production dabatase we don t have access to With a mock we can fake a method to do or return anything we want Our first test is called ItShouldLoadAllClients Since our test naming skills are so incredibly sharp we can imply just by reading that title that a clients list has to be loaded during Presenter class initialization We first create a new method called SetUp that will run right before each time a test method runs to set everything up in this case it will initialize mock instances for the repository class and view interface We then proceed to create an instance of the Presenter class which is the test subject our lab rat yes and then we use the Verify method of the mock that will throw a nasty exception and make the unit test fail miserably if the specified View method LoadClients for this particular case was never called during Presenter initialization using Moq using NUnit Framework using System Collections Generic using System Linq namespace Codenough Demos WinFormsMVP TestFixture public class WhenClientsWindowLoads private Mock IClientsView clientsViewMock private Mock ClientRepository clientsRepositoryMock SetUp public void SetUp this clientsViewMock new Mock IClientsView this clientsRepositoryMock new Mock ClientRepository Test public void ItShouldLoadAllClients Act var clientsPresenter new ClientsPresenter clientsViewMock Object clientsRepositoryMock Object Assert clientsViewMock Verify view view LoadClients It IsAny IList ClientModel Expected clients to be loaded on initialization Of course this test passes A call to the LoadClients method is done at the Presenter constructor The following tests are a little more complicated since we will be setting up methods of the View and repository mocks to return what we need them to return method setup Our next test is ItShouldShowFirstClientOnListDetails which requires our presenter to load the first client on the list after initialization For this case we let the SetUp method do its thing and create the respective mocks and then at our test arrange phase we use the Setup method to make the repository mock return a sample list of clients when the FindAll method is called Finally we verify the LoadClient method of the view was called making this the assertion that makes the test case pass and make us happy or fail and quit our jobs Test public void ItShouldShowFirstClientOnListDetails Arrange var clients new List ClientModel new ClientModel Id 1 Name Matt Dylan Age 28 Gender Male Email mattd none com new ClientModel Id 2 Name Anna Stone Age 22 Gender Female Email ann none com clientsRepositoryMock Setup repository repository FindAll Returns clients Act var clientsPresenter new ClientsPresenter clientsViewMock Object clientsRepositoryMock Object Assert clientsViewMock Verify view view LoadClient clients First Expected first client to be loaded on initialization The last test is ItShouldShowClientDetailsOnListItemSelected and finding out the way it works will be your homework dear reader This is the most complicated of them all since now we use Moq to fire view events and wake up the Presenter which should be listening to them Test public void ItShouldShowClientDetailsOnListItemSelected Arrange var clients new List ClientModel new ClientModel Id 1 Name Matt Dylan Age 28 Gender Male Email mattd none com new ClientModel Id 2 Name Anna Stone Age 22 Gender Female Email ann none com clientsRepositoryMock Setup repository repository FindAll Returns clients clientsRepositoryMock Setup repository repository GetById 1 Returns clients First clientsViewMock SetupGet view view SelectedClient Returns clients First var clientsPresenter new ClientsPresenter clientsViewMock Object clientsRepositoryMock Object Act clientsViewMock Raise view view ClientSelected null Assert clientsViewMock Verify view view LoadClient clients First Expected first client to be loaded on initialization Conclusion Making code testable is not easy at all No really AT

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

  • programming | Informatech CR Blog
    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 April 10 2013 by Edwin Dalorzo Categories Java Programming Tags ceylon java null pointer programming sml 23 Comments Review of Programming Languages Course from Coursera I just finished taking the course Programming Languages by Dan Grossman from the University of Washington in Coursera and this post is a review of the course from my perspective Programming Languages is a course intended to teach many important principles in programming with a strong emphasis in functional programming Among the most interesting concepts are the contrasts between static and dynamic typing and type inference and the contrasts between functional programming and object oriented programming But The course covers other fundamental concepts like mutability immutability algebraic data types and pattern matching recursion and tail recursion first class functions and closures high order programming currying modules parametric polymorphism thunks and lazy evaluation streams memoization macros object oriented inheritance mixins and many other interesting topics Every week a set of topics is covered in great detail in a series of videos that may have a length between 10 to 20 minutes The material is released every week as course progresses The materials covered in the videos are also provided in written format for further analysis and easier reviewing Every week a homework is made available to the students The homework consists of a series of exercises of increasing difficulty Sometimes the homework contains challenge exercises that can be solved for some extra points In my case solving every homework took an average time between 4 to 8 hours and the challenge exercises sometimes took me almost a similar amount time mostly due to the lack of specification and not necessarily due to their complexity although they were more complex than the rest of the exercises in the homework Students submit their homework and an automatic grading system reviews it by applying a series of tests The failing tests are reported to the students so that they can fix the problems and resubmit again Only the first two submissions count for the final grade an average is used for final grading purposes although students are allowed to submit as many times as they want The grading system works pretty well but there were occasional problems with it that were timely corrected Perhaps my biggest complaint is that the autograder many times does not provided enough information to determine what was wrong with the homework submission and this lead to certain amount of frustration when trying to figure out what to do to solve the problems above all because only the first two submissions count for the final grade Particularly for the cases of challenge exercises the information provided by the autograder upon failure of any tests was really scarce Also students are required to submit their homework for peer reviews And they are required to peer review other students homework This exercise is intended to give a broader perspective to the students by means of reading someone else s code This way the student can find better solutions created by others or spot problems in their own solutions etc Also during the peer review process the right best solutions for the exercises were shared with all students participating in the reviews Therefore doing the reviews was the best way to find out the answers to all exercises in the homework On week 4 and week 8 the students take an online exam consisting in questions with multiple selection answers The questions are based on the topics covered in previous weeks Some of the questions could be based on understanding of the theoretical concepts and some question consist in practical applications of those concepts Once the student starts the exam there is a time limit to complete it I think something around 90 minutes The following is detailed outline of the topics covered every week Week 1 SML ML Expressions and Variable Bindings Variables are Immutable Function Bindings Pairs and Other Tuples Lists Let Expressions Options Some Other Expressions and Operators Lack of Mutation and Benefits Thereof The Pieces of a Programming Language The homework consisted in the development of series of functions to deal with dates Week 2 SML Conceptual Ways to Build New Types Records By Name vs By Position Syntactic Sugar and the Truth about Tuples Datatype Bindings How ML Does Not Provide Access to Data Type Values How ML Provides Access to Datatype Values Case Expressions Type Synonyms Lists and Options Are Datatypes Polymorphic Datatypes Pattern Matching Type Inference Polymorphic Types and Equality Types Nested Patterns Exceptions Tail Recursion and Accumulators The homework consisted in a series of exercises related to a card game a variation of solitaire Week 3 SML Functions as Arguments Polymorphic Types and Functions as Arguments Anonymous Functions Unnecessary Function Wrapping Maps and Filters Returning Functions Lexical Scope Environments and Closures Fold Combining Functions Currying and Partial Application The Value Restriction Mutation via ML References Callbacks Abstract Datatypes Closures in Other Languages The homework consisted in a series of exercises related to the implementation of pattern matching and type inference Week 4 SML What is Type Inference Overview of ML Type Inference Mutual Recursion Modules for Namespace Management Signatures Hiding Things Equivalent Implementations Benefits of Side Effect Free Programming Standard Equivalences There was not homework because this week was the week of the midterm exam Week 5 Racket Racket vs Scheme Functions Lists Syntax and Parentheses Dynamic Typing Local Bindings Top Level Definitions Mutability Immutability Delayed Evaluation with Thunks Lazy Evaluation Streams Memoization Macros The homework consisted in the implementation of exercises related to streams and the challenge was about defining macros Week 6 Racket Datatype Programming without Datatypes Recursive Datatypes via Racket Lists Recursive Datatypes via Racket s struc Implementing Programming Languages Interpreters and Compilers Implementing Closures Defining Macros via Functions in the Metalanguage ML versus Racket What Is Static Checking Correctness Soundness Completeness Undecidability Weak Typing Advantages and Disadvantages of Static Checking The homework consisted in the implementation of an interpreter for small programming language called MUPL Made Up Programming Language Week 7 Ruby Objects Classes Methods Variables Visibility and Getters Setters Everything is an Object Duck Typing Arrays Blocks Hashes and Ranges Subclassing and Inheritance Overriding and Dynamic Dispatch Method Lookup Definition Dynamic Dispatch versus Closures The homework consisted in the implementation of a tetris game Week 8 Ruby OOP Versus Functional Decomposition Multimethods Mutiple Inheritance Mixins Abstract Methods The Subtyping Relation Function Subtyping Subtyping for OOP Covariance Generics Versus Subtyping Bounded Polymorphism The homework consisted in the implementation of an interpreter for a small language of two dimensional geometric objects Final Thoughts In my opinion this is one of the best courses I have ever taken It was fascinating the topics were covered in great detail The professor Grossman explained every topic with plenty of examples and almost all the homework was really interesting and the problems were increasingly challenging Having the opportunity to work with different programming languages of different paradigms and typing styles really enriched my understanding of how programming languages work and how to make proper comparisons between their features It was particularly interesting the effort of converting some implementations of solutions to some problems from functional code to object oriented code I think that the course prepares the students to learn and assimilate other programming languages more rapidly by having covered concepts that are typically seen in other languages just with different syntax From the entire course I found the sections covering Ruby a little bit more uninteresting and particularly the homework for the tetris game in week 7 was too simple and I found little could be learn from solving the exercise but the rest of the material and homework were incredibly well thought and prepared The entire experience was really enriching and I feel that it has made me a better developer and has broadened my understand of programming languages and has rekindled my enthusiasm to learn even more about programming and other programming languages It is definitely a course that I would highly recommend to any other developers Share this Email Facebook Twitter Like this Like Loading March 25 2013 by Edwin Dalorzo Categories Programming Tags coursera programming 2 Comments Java Streams API Preview For today s post I want to share a series of examples that I have developed while trying the latest features in the Java 8 Stream API In my last post I did a comparison of the features with those available in LINQ and for today s post I have decided to go a bit further and try to use the API to work with a small domain model The examples developed here are based on the same examples presented in the LambdaJ Project The Data Model For the examples I will use the following domain model You can see a full implementation of all the examples developed here by downloading the following Gist For the examples presented below assume that in the context of the code there are three streams always available Stream Person persons Stream Car cars Stream Sale sales Challenge 1 Print All Car Brands From a collection of cars print all car brands StringJoiner brands cars map Car getBrand collect toStringJoiner String allBrands brands toString For this example I have also use the new StringJoiner class Challenge 2 Select all Sales on Toyota From a collection of sales select all those that are related to Toyota cars List Sale toyotaSales toyotaSales sales filter s s getCar getBrand equals Toyota collect toList toyotaSales forEach System out println For this example I could have also used the forEach method in the stream to get all the sales printed I did it this way just to illustrate that it is possible to collect all items in the stream into a list and from there we can process them But ideally I should have processed the items directly in the stream Challenge 3 Find Buys of the Youngest Person From a collection of sales find all those that are from the youngest buyer ToIntFunction Entry Person List Sale byAge byAge e e getKey getAge byYoungest sales collect groupingBy Sale getBuyer entrySet stream sorted comparing byAge map Entry getValue findFirst if byYoungest isPresent System out println byYoungest get Challenge 4 Find Most Costly Sale From a collection of sales find the most costly of all of them Optional Sale mostCostlySale Comparator Sale byCost comparing ToDoubleFunction Sale Sale getCost reverseOrder mostCostlySale sales sorted byCost findFirst if mostCostlySale isPresent System out println mostCostlySale get Challenge 5 Sum of Sales from Male Buyers Sellers From a collection of sales find the sum of all buys sells made by men double sum sales filter s s getBuyer isMale s getSeller isMale mapToDouble Sale getCost sum Challenge 6 Find the Age of the Youngest Buyer From a collection of sales find the age of the youngest buyer who bought for more than 40 000 OptionalInt ageOfYoungest ageOfYoungest sales filter sale sale getCost 40000 map Sale getBuyer mapToInt Person getAge sorted findFirst if ageOfYoungest isPresent System out println ageOfYoungest getAsInt Challenge 7 Sort Sales by Cost Sort a collection of sales by cost Comparator Sale byCost comparing ToDoubleFunction Sale Sale getCost List Sale sortedByCost sortedByCost sales sorted byCost collect toList Challenge 8 Index Cars by Brand From a collection of cars index cars by the their brand Map String List Car byBrand byBrand cars collect groupingBy Car getBrand Challenge 9 Find Most Bought Car From a collection of sales find the most bought car ToIntFunction Entry Car List Sale toSize e e getValue size Optional Car mostBought mostBought sales collect groupingBy Sale getCar entrySet stream sorted comparing toSize reverseOrder map Entry getKey findFirst if 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 March 25 2013 by Edwin Dalorzo Categories Java Programming Tags jdk8 lambda programming streams 16 Comments Java Streams Preview vs Net High Order Programming with LINQ In today s post I want to share with you a comparison that I did this weekend between the high order programming features from LINQ and those being incorporated into the new Java 8 streams API It is important to highlight that the Java Stream API is still work in progress I have been downloading and building the source code of Project Lambda for almost a year now and I have seen how the API evolves over time but the improvements are more frequent as we approach the general availability date planed for September 2013 Before I delve into the comparisons I must say that as of today the current implementation of the Java Stream API is far away from all the high order programming functionality offered by LINQ It has already been announced in the mailing list that there was not going to be enough time for all improvements originally planned and the JEP 108 Collection Enhancements for Third party Libraries has been deferred to future releases of Java I am not sure how much of the Stream API is going to be affected by this decision but I hope that in the remaining months prior to the release they do much more improvements in the current API at least bring it closer to LINQ At any rate as of today it appears that some basic functionality is already covered filter map reduce sort etc but much more work is still needed for this API to be decently compared to LINQ in terms of functionality and my comparison here only focuses particularly in the high order programming features So I really hope that it is only too early to write this article and in the coming months things are going to improve dramatically Also there are some inherent problems that have been evidently difficult to overcome One of those affecting the design of the API is the lack of value types in Java It appears that the expert group have been struggling with this and their solution has been to make copies of some interfaces defining some to deal with primitive types i e IntStream LongStream DoubleStream and others with reference types i e Stream This has also caused a diaspora of copies of other functional interfaces aka interface polution particularly in the case of the interface Function the problem is much more evident i e ToIntFunction ToLongFunction ToDoubleFunction and Function Even when all this repetition is done to alleviate the performance problems inherent to boxing and unboxing of primitive types this workaround has undesirable side effects first the need to overload methods for everyone of these interfaces This overloading is undesirable because it makes it impossible to use a clean lambda expression for these cases since the compiler is incapable to determine which of all the argument functional interfaces is the one being implemented by the lambda So to avoid compiler errors we are forced to use awful type castings in the code which make it more verbose and look pretty bad And a secondary side effect is the incompatibility between primitive type and reference type collections i e an Stream Integer is not the same as an IntStream About the Comparison For this exercise I took the code examples from the book Net 4 0 Generics a Beginners Guide by Sudipta Mukherjee particularly his examples from Chapter 4 LINQ to Objects I did not do all the examples simply because there are many features still lacking in the Java Stream API which make it impossible to replicate the same functionality The author of the book makes all these examples to demonstrate LINQ high order programming functionality It is not my intention to write an article on LINQ and all it can do but a comparison of what I could do with the high order programming features in the Stream API today if I wanted to implement similar idioms as those I can so easily implement using LINQ functionality 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 Therefore this article is based on my understanding of his view of this part of LINQ in order to make a comparison but I can understand that LINQ is more than just a bunch of high order functions Now some may argue that there is no intention in making the stream API something comparable to LINQ which may well be 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 at least initially yet I feel that it is still a good benchmark to compare the power of expressiveness in this new Java API For me this gives me an idea of how evolved this API is today when compared to the power of expressiveness of this another state of art technology As it is customary in the internet world others may freely disagree with me and present their personal perspectives as I did here For the cases that I could implement the examples are based on the use of Stream and IntStream classes and the static methods available on the Streams and Collectors helper classes In order to keep it simple and readable I am not showing in the code examples below all the imports and static imports that I used For that matter you may want to take a look at the following Gist where I have published most of these examples and where you will be able to see full imports needed to make the code run properly Restriction Operators Challenge 1 Filtering Say we have a List of names and we would like to find all those names where am occurs LINQ string names Sam Pamela Dave Pascal Erik List string filteredNames names Where c c Contains am ToList Java Streams String names Sam Pamela Dave Pascal Erik List String filteredNames stream names filter c c contains am collect toList Challenge 2 Indexed Filtering Find all the names in the array names where the length of the name is less than or equal to the index of the element 1 LINQ string names Sam Pamela Dave Pascal Erik var nameList names Where c index c Length index 1 ToList Java Streams Now this one was particularly tricky in Java because as of today the API for streams does not contain any methods that indicate the index of an element within the stream So I was forced to generate an indexed stream out of the original array String names Sam Pamela Dave Pascal Erik List String nameList Stream Integer indices intRange 1 names length boxed nameList zip indices stream names SimpleEntry new filter e e getValue length e getKey map Entry getValue collect toList Now the lack of indices in the stream made the algorithm more verbose but it was also interesting to notice the incompatibilities between primitive type streams like IntStream and reference type streams like Stream Integer In this case I was forced to transform the IntStream returned by intRange into a Stream Integer in order to make the argument compatible with the types expected by zip as you can see in the line 4 Projection Operators Challenge 3 Selecting Mapping Say we have a list of names and we would like to print Hello in front of all the names LINQ List string nameList1 new List Anders David James Jeff Joe Erik nameList1 Select c Hello c ToList ForEach c Console WriteLine c Java Streams List String nameList1 asList Anders David James Jeff Joe Erik nameList1 stream map c Hello c forEach System out println Challenge 4 Selecting Many Flattening Suppose we have a dictionary such that each key has a list of values attached to them Now we want to project all the elements in a single collection LINQ Dictionary string List string map new Dictionary string List string map Add UK new List string Bermingham Bradford Liverpool map Add USA new List string NYC New Jersey Boston Buffalo var cities map SelectMany c c Value ToList Java Streams Once more the Java syntax as of today is a bit more verbose First we must transform the map to an entry set and from there we can generate a stream that we can later flatten to a list of cities as follows Map String List String map new LinkedHashMap map put UK asList Bermingham Bradford Liverpool map put USA asList NYC New Jersey Boston Buffalo FlatMapper Entry String List String String flattener flattener entry consumer entry getValue forEach consumer List String cities map entrySet stream flatMap flattener collect toList Ideally the lines 5 6 should be defined as inline arguments of flatMap but the compiler cannot properly infer the types of the expression precisely for the overloading problems that I described above Given the amount of type information that must be provided I felt that it was best to define it in another line as I did in 5 and 6 It looks awful I know Clearly we are in desperate need of an API that offers operations to deal with maps or tuples Partitioning Operators Challenge 5 Taking an Arbitrary Number of Items In this case we are interested in evaluating only the first n elements of a collection For instance using a finite list of numbers obtain the first 4 of them LINQ int numbers 1 2 3 4 5 6 7 8 9 10 11 12 13 var first4 numbers Take 4 ToList Java Streams Once more in Java the absence of value types forced me to make a conversion from an IntStream into a Stream Integer to make this work see line 5 basically because there is not value type collector An alternative would have been to consume the stream itself i e forEach or to collect items into an array using Stream toArray method int numbers 1 2 3 4 5 6 7 8 9 10 11 12 13 List Integer firstFour firstFour stream numbers limit 4 boxed collect toList Challenge 6 Taking Items Based on Predicate In this case we are interested in taking items out of a collection as long as they satisfy a predicate Once we find an item that does not satisfy the predicate we 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

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

  • Programming | Informatech CR Blog | Page 2
    that special care had been taken in the consistency and polish of the interface Both were very much welcome In full day to day usage the UI shines though where I felt the most joy was in the touch keyboard It is absolutely a pleasure to use no gestures or swipes straight taps and by far it s the best of any smartphone that I ve used The camera was another pleasant surprise The capture and photo browser were excellent behold The multitasking also requires a bit of getting used to as a long press of the back key will allow you to get an open app list however it will not let you kill any You have to jump in and continually press back until you exit To finish off the stock functionality the People hub was generally useful even though the Google contacts were indeed not wholly sync d It gave quick access to recent contacts and integrated well with social networks Even though Facebook is integrated in the way to properly see your Newsfeed is through the standalone app Which sadly is not developed by FB and is quite honestly sub par to similar offerings on iOS and Android WhatsApp was a similar story the implementation is not up to par with the other platforms and more annoyingly it activated the music controls and gobbled battery As a workaround you have to download a separate app that kills the music controls and run it periodically The app also seemed to implode under heavily used group chats Even with the mediocrity of third party apps I can honestly say the OS is pleasant to use and the tiles are colorful and attractive So rounding out Pros Superb interface extremely polished Quite simply the best touch keyboard I ve ever used on any smartphone Integration between social networks and contacts is almost seamless Excellent camera Lumia hardware is very capable and attractive Integration with Microsoft services is predictably good Cons Synchronization with Google services is poor especially now that ActiveSync was retired App selection and most importantly quality is low low low Years behind iOS and Android WhatsApp drains the battery and requires Stop the Music to kill it every once in a while Multitasking does not allow you close the application from the app list WP 7 8 Lack of a centralized notification area is confusing Conclusion If you re a Hotmail user and you live your life in Exchange and Microsoft Office Windows Phone is a natural fit The Lumia hardware is capable and attractive the UI is very polished and if you can live with the poor app selection and quality you ll enjoy it However if you use Google services and have gotten used to the abundance of other app stores the UI may not compensate the tradeoffs for functionality you would have to give up In the future this may change but at present it s too much to take 9 933333 84 083333 Share this Email Facebook Twitter Like this Like Loading June 13 2013 by pjpalm801 Categories Mobile Tags lumia windowsphone Leave a comment Memoized Fibonacci Numbers with Java 8 Since today is Fibonacci Day I decided that it would be interesting to publish something related to it I believe one of the first algorithms we all see when learning non linear recursion is that of calculating a Fibonacci number I found a great explanation on the subject in the book Structure and Interpretation of Computer Programs SIC and I dedicated some time to playing with the Fibonacci algorithm just for fun While doing so I found an interesting way to improve the classical recursive algorithm by using one of the new methods added in Java 8 in the Map interface and which I used here to implement a form of memoization Classical Recursive Fibonacci In the classical definition of Fibonacci we learn that We program this very easily in Java public static long fibonacci int x if x 0 x 1 return x return fibonacci x 1 fibonacci x 2 Now the problem with this algorithm is that with the exception of the base case we recursively invoke our function twice and interestingly one of the branches recalculates part of other branch every time we invoke the function Consider the following image taken from SIC that represents an invocation to fibonacci 5 Clearly the branch to the right is redoing all the work already done during the recursive process carried out by the left branch Can you see how many times fibonacci 2 was calculated The problem gets worse as the function argument gets bigger In fact this problem is so serious that the calculation of a small argument like fibonacci 50 might take quite a long time Memoized Recursive Fibonacci However there is a way to improve the performance of the original recursive algorithm I mean without having to resort to a constant time algorithm using for instance Binet s formula The serious problem we have in the original algorithm is that we do too much rework So we could alleviate the problem by using memoization in other words by providing a mechanism to avoid repeated calculations by caching results in a lookup table that can later be used to retrieve the values of already processed arguments In Java we could try to store the Fibonacci numbers in a hast table or map In the case of the left branch we ll have to run the entire recursive process to obtain the corresponding Fibonacci sequence values but as we 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 May 8 2013 by Edwin Dalorzo Categories Java Tags fibonacci java 7 Comments Java 8 Optional Objects In this post I present several examples of the new Optional objects in Java 8 and I make comparisons with similar approaches in other programming languages particularly the functional programming language SML and the JVM based programming language Ceylon this latter currently under development by Red Hat I think it is important to highlight that the introduction of optional objects has been a matter of debate In this article I try to present my perspective of the problem and I do an effort to show arguments in favor and against the use of optional objects It is my contention that in certain scenarios the use of optional objects is valuable but ultimately everyone is entitled to an opinion and I just hope this article helps the readers to make an informed one just as writing it helped me understand this problem much better About the Type of Null In Java we use a reference type to gain access to an object and when we don t have a specific object to make our reference point to then we set such reference to null to imply the absence of a value In Java null is actually a type a special one it has no name we cannot declare variables of its type or cast any variables to it in fact there is a single value that can be associated with it i e the literal null and unlike any other types in Java a null reference can be safely assigned to any other reference types See JLS 3 10 7 and 4 1 The use of null is so common that we rarely meditate on it field members of objects are automatically initialized to null and programmers typically initialize reference types to null when they don t have an initial value to give them and in general null is used everywhere to imply that at certain point we don t know or we don t have a value to give to a reference About the Null Pointer Reference Problem Now the major problem with the null reference is that if we try to dereference it then we get the ominous and well known NullPointerException When we work with a reference obtained from a different context than our code i e as the result of a method invocation or when we receive a reference as an argument in a method we are working on we all would like to avoid this error that has the potential to make our application crash but often the problem is not noticed early enough and it finds its way into production code where it waits for the right moment to fail which is typically a Friday at the end of the month around 5 p m and just when you are about to leave the office to go to the movies with your family or drink some beers with your friends To make things worse the place where your code fails is rarely the place where the problem originated since your reference could have been set to null far away from the place in your code where you intended to dereference it So you better cancel those plans for the Friday night It s worth mentioning that this concept of null references was first introduced by Tony Hoare the creator of ALGOL back in 1965 The consequences were not so evident in those days but he later regretted his design and he called it a billion dollars mistake precisely referring to the uncountable amount of hours that many of us have spent since then fixing this kind null dereferencing problems Wouldn t it be great if the type system could tell the difference between a reference that in a specific context could be potentially null from one that couldn t This would help a lot in terms of type safety because the compiler could then enforce that the programmer do some verification for references that could be null at the same time that it allows a direct use of the others We see here an opportunity for improvement in the type system This could be particularly useful when writing the public interface of APIs because it would increase the expressive power of the language giving us a tool besides documentation to tell our users that a given method may or may not return a value Now before we delve any further I must clarify that this is an ideal that modern languages will probably pursue we ll talk about Ceylon and Kotlin later but it is not an easy task to try to fix this hole in a programming language like Java when we intend to do it as an afterthought So in the coming paragraphs I present some scenarios in which I believe the use of optional objects could arguably alleviate some of this burden Even so the evil is done and nothing will get rid of null references any time soon so we better learn to deal with them Understanding the problem is one step and it is my opinion that these new optional objects are just another way to deal with it particularly in certain specific scenarios in which we would like to express the absence of a value Finding Elements There is a set of idioms in which the use of null references is potentially problematic One of those common cases is when we look for something that we cannot ultimately find Consider now the following simple piece of code used to find the first fruit in a list of fruits that has a certain name public static Fruit find String name List Fruit fruits for Fruit fruit fruits if fruit getName equals name return fruit return null As we can see the creator of this code is using a null reference to indicate the absence of a value that satisfies the search criteria 7 It is unfortunate though that it is not evident in the method signature that this method may not return a value but a null reference Now consider the following code snippet written by a programmer expecting to use the result of the method shown above List Fruit fruits asList new Fruit apple new Fruit grape new Fruit orange Fruit found find lemon fruits some code in between and much later on or possibly somewhere else String name found getName uh oh Such simple piece of code has an error that cannot be detected by the compiler not even by simple observation by the programmer who may not have access to the source code of the find method The programmer in this case has naively failed to recognize the scenario in which the find method above could return a null reference to indicate the absence of a value that satisfies his predicate This code is waiting to be executed to simply fail and no amount of documentation is going to prevent this mistake from happening and the compiler will not even notice that there is a potential problem here Also notice that the line where the reference is set to null 5 is different from the problematic line 7 In this case they were close enough in other cases this may not be so evident In order to avoid the problem what we typically do is that we check if a given reference is null before we try to dereference it In fact this verification is quite common and in certain cases this check could be repeated so many times on a given reference that Martin Fowler renown for hist book on refactoring principles suggested that for these particular scenarios such verification could be avoided with the use of what he called a Null Object In our example above instead of returning null we could have returned a NullFruit object reference which is an object of type Fruit that is hollowed inside and which unlike a null reference is capable of properly responding to the same public 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 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 April 10 2013 by Edwin Dalorzo Categories Java Programming Tags ceylon java null pointer programming sml 23 Comments Overview Of The Task Parallel Library TPL Introduction Remember those times when we needed to spawn a separate thread in order to execute long running operations without locking the application execution until the operation execution completes Well time to rejoice those days are long gone Starting by its version 4 5 the Microsoft NET Framework delivers a new library that introduces the concept of tasks This library is known as the Task Parallel Library or TPL Tasks v s Threads In the good annoying old days we frequently had the need to spawn a separate thread to query the database without locking the main application thread so we could show a loading message to the user and wait for the query to finish execution and then process results This is a common scenario in desktop and mobile applications Even though there are several ways to spawn background threads async delegates background workers and such in the most basic and rudimentary fashion things went a little something like this User user null Create background thread that will get the user from the repository Thread findUserThread new Thread user DataContext Users FindByName luis aguilar Start background thread execution findUserThread Start Console WriteLine Loading user Block current thread until background thread finishes assigning a value to the user variable findUserThread Join At this point the user variable contains the user instance loaded from the repository Console WriteLine User loaded Name is user Name Once again this code is effective it does what it has to do Load a user from a repository and show the loaded user s name on console However this code sacrifices succinctness completely in order to initialize run and join the background thread that loads the user asynchronously The Task Parallel Library introduces the concept of tasks Tasks are basically operations to be run asynchronously just like what we just did using thread notation This means that we no longer speak in terms of threads but tasks instead which lets us execute asynchronous operations by writing very little amount of code which also is a lot easier to understand and read Now things have changed for good like this Console WriteLine Loading user Create and start the task that will get the user from the repository var findUserTask Task Factory StartNew DataContext Users FindByName luis aguilar The task Result property hold the result of the async operation If the task has not finished it will block the current thread until it does Pretty much like the Thread Join method var user findUserTask Result Console WriteLine User loaded Name is user Name A lot better huh Of course it is Now we have the result of the async operation strongly typed Pretty much like using async delegates but without all the boilerplate code required to create delegates which is possible thanks to the power of C lambda expressions and built in delegates Func Action Predicate etc Tasks have a property called Result This property contains the value returned by the lambda expression we passed to the StartNew method What happens when we try to access this property while the task is still running Well the execution of the calling method is halted until the task finishes This behavior is similar to Thread Join line 16 of the first code example Tasks Continuations OK we now have knowledge of how all this thing about tasks goes But let s assume you don t want to block the calling thread execution until the task finishes but have it call another task after it finishes that will do something with the result later on For such scenario we have task continuations The Task Parallel Library allows us to chain tasks together so they are executed one after another Even better code to achieve this is completely fluent and verbose Console WriteLine Loading user Create tasks to be executed in fluent manner Task Factory StartNew User DataContext Users FindByName luis aguilar First task ContinueWith previousTask This will execute after the first task finishes First task s result is passed as the first argument of this lambda expression var user previousTask Result Console WriteLine User loaded Name is user Name Tasks will start running asynchronously You can do more things here As verbose as it gets you can read the previous code like Start new task to find a user by name and continue by printing the user name on console Is important to notice that the first parameter of the ContinueWith method is the previously executed task which allows us to access its return value through its Result property Async And Await The Task Parallel Library means so much for the Microsoft NET Framework that new keywords were added to all its languages specifications to deal with asynchronous tasks These new keywords are async and await The async keyword is a method modifier that specifies that it is to be run in parallel with the caller method Then we have the await keyword which tells the runtime to wait for a task result before assigning it to a local variable in the case of tasks which return values or simply wait for the task to finish in the case of those with no return value Here is how it works 1 Awaiting For Tasks With Result async void LoadAndPrintUserNameAsync Create start and wait for the task to finish then assign the result to a local variable var user await Task Factory StartNew User DataContext Users FindByName luis aguilar At this point we can use the loaded user Console WriteLine User loaded Name is user Name 2 Awaiting For Task With No Result async void PrintRandomMessage Create start and wait for the task to finish await Task Factory StartNew Console WriteLine Not doing anything really 3 Usage void RunTasks Load user and print its name LoadAndPrintUserNameAsync Do something else

    Original URL path: http://blog.informatech.cr/category/programming-2/page/2/ (2015-08-19)
    Open archived version from archive

  • Overview Of The Task Parallel Library (TPL) | Informatech CR Blog
    line 16 of the first code example Tasks Continuations OK we now have knowledge of how all this thing about tasks goes But let s assume you don t want to block the calling thread execution until the task finishes but have it call another task after it finishes that will do something with the result later on For such scenario we have task continuations The Task Parallel Library allows us to chain tasks together so they are executed one after another Even better code to achieve this is completely fluent and verbose Console WriteLine Loading user Create tasks to be executed in fluent manner Task Factory StartNew User DataContext Users FindByName luis aguilar First task ContinueWith previousTask This will execute after the first task finishes First task s result is passed as the first argument of this lambda expression var user previousTask Result Console WriteLine User loaded Name is user Name Tasks will start running asynchronously You can do more things here As verbose as it gets you can read the previous code like Start new task to find a user by name and continue by printing the user name on console Is important to notice that the first parameter of the ContinueWith method is the previously executed task which allows us to access its return value through its Result property Async And Await The Task Parallel Library means so much for the Microsoft NET Framework that new keywords were added to all its languages specifications to deal with asynchronous tasks These new keywords are async and await The async keyword is a method modifier that specifies that it is to be run in parallel with the caller method Then we have the await keyword which tells the runtime to wait for a task result before assigning it to a local variable in the case of tasks which return values or simply wait for the task to finish in the case of those with no return value Here is how it works 1 Awaiting For Tasks With Result async void LoadAndPrintUserNameAsync Create start and wait for the task to finish then assign the result to a local variable var user await Task Factory StartNew User DataContext Users FindByName luis aguilar At this point we can use the loaded user Console WriteLine User loaded Name is user Name 2 Awaiting For Task With No Result async void PrintRandomMessage Create start and wait for the task to finish await Task Factory StartNew Console WriteLine Not doing anything really 3 Usage void RunTasks Load user and print its name LoadAndPrintUserNameAsync Do something else PrintRandomMessage As you can see asynchronous methods are now marked with a neat async modifier As I mentioned before that means they are going to run asynchronously better said in a separate thread Is important to clarify that asynchronous methods can contain multiple child tasks inside them which are going to run in any order but by marking the method as asynchronous means that when it is called in

    Original URL path: http://blog.informatech.cr/2013/04/05/overview-of-the-task-parallel-library/ (2015-08-19)
    Open archived version from archive

  • Unit Testing 101: Inversion Of Control | Informatech CR Blog
    User user DataContext Users GetByName userName string hashedPassword this passwordHasher Hash password Set the user new password user Password hashedPassword Save the user back to the database DataContext Users Update user DataContext Commit More methods public interface IPasswordHasher string Hash string plainTextPassword public class Md5PasswordHasher IPasswordHasher public string Hash string plainTextPassword Hash password using an encryption algorithm Inversion of Control is usually implemented by applying a design pattern called the Strategy Pattern as defined in The Gang Of Four book This pattern consists on abstracting concrete component and algorithm implementations from the rest of the classes by exposing only an interface they can use thus making implementations interchangeable at runtime and encapsulate how these implementations work since any class using them should not care about how they work So in order to achieve this we need to sort some things out Abstract an interface from the Md5PasswordHasher class IPasswordHasher so anyone can write custom implementations of password hashers line 28 31 Mark the Md5PasswordHasher class as an implementation of the IPasswordHasher interface line 33 Change the type of the password hasher used by UserManager to IPasswordHasher line 3 Add a new constructor parameter of type IPasswordHasher interface line 5 which is the instance the UserManager class will use to hash its passwords This way we delegate the creation of dependencies to the user of the class and allows the user to provide any implementation it wants allowing it to control how the password is going to be hashed This is the very essence of inversion of control Minimize class coupling The user of the UserManager class has now control over how passwords are hashed Password hashing control has been inverted from the class to the user Here is an example on how we can specify the only dependency of the UserManager class IPasswordHasher md5PasswordHasher new Md5PasswordHasher UserManager userManager new UserManager md5PasswordHasher userManager ResetPassword luis aguilar 12345 So Why is this useful Well we can go crazy and create our own hasher implementation to be used by the UserManager class Plain text password hasher public class PlainTextPasswordHasher IPasswordHasher public string Hash string plainTextPassword Let s disable password hashing by returning the plain text password return plainTextPassword Usage IPasswordHasher plainTextPasswordHasher new PlainTextPasswordHasher UserManager userManager new UserManager plainTextPasswordHasher Resulting password will be 12345 userManager ResetPassword luis aguilar 12345 Conclusion So this concludes our article on Inversion of Control Hopefully with a little more practice you will be able to start applying this to your code Of course the biggest benefit of this technique is related to unit testing So What does it has to do with unit testing Well we re going to see this when we get into type mocking So stay tuned Further Reading The Strategy Pattern by OODesign Design Patterns Elements of Reusable Object Oriented Software book at Amazon Share this Email Facebook Twitter Like this Like Loading Related April 3 2013 by Luis Aguilar Categories NET Programming 6 Comments Post navigation Unit Testing 101 Basics Overview Of The Task

    Original URL path: http://blog.informatech.cr/2013/04/03/unit-testing-101-inversion-of-control/ (2015-08-19)
    Open archived version from archive

  • Unit Testing 101: Basics | Informatech CR Blog
    specific condition Should return true if validation is successful Running Tests Once you have your fixture ready to go is now time to run all tests on it and see results I will be using the NUnit GUI Runner which looks for all classes in the assembly marked with the TestFixture attribute and then calls each method on them marked with the Test attribute Is important to remember that all tests must be in a separate class library First reason is because it is a good practice you should not be mixing application code with test code and second because the NUnit test runner can only load DLL files So first thing to do is to build the project so we have a DLL containing all our tests Once we have a DLL file with our test fixture classes on it fire up the NUnit test runner NUnit exe and load the file on it At this point everything is quite intuitive You can hit the Run button and see how all tests pass or rebuild the project on Visual Studio and see how the test runner auto updates with new changes Cool huh Arrange Act and Assert Test methods are usually composed of three common phases Arrange act and assert Or triple A if you like Arrange At the very beginning of the method you need to setup the test scenario This includes expected test results for comparison with actual results instances of the components to be tested and type mocking Act After arrangement is done we now have to actually perform the actions that will produce the actual test results For instance call the Validate method on the UserAuthenticator class which performs the actual user validation Assert The assertion phase verifies that actual tests results match what we are expecting Is a good practice to provide comments delimiting each phase Test public void ShouldReturnTrueValidationIsSuccessful Arrange var expectedResult true var userAuthenticator new UserAuthenticator Act var actualResult userAuthenticator Validate luis aguilar 1234 Assert Assert That actualResult Is EqualTo expectedResult message Authentication failed though it should have succeeded As you might see these three phases are executed in order Is a good practice to initialize variables with expected results at Arrange phase to make the Assert phase more readable Also for the sake of readability I am using the Assert That syntax of NUnit so assertions are more verbose Tests Before Implementation Even though unit testing is good for all development methodologies I m an avid supporter of the Test Driven Development TDD methodology As the name implies TDD is all about writing all tests BEFORE you implement actual application code That way your code will meet acceptance criteria right from inception Basically application infrastructure design is driven by tests Now we think on user requirements rather than UML diagrams and classes For instance you should write all the previous sample tests before implementing the UserAuthenticator class That way that particular class will be born satisfying user requirements so we don

    Original URL path: http://blog.informatech.cr/2013/03/29/unit-testing-101-basics/ (2015-08-19)
    Open archived version from archive

  • UI Design Using Model-View-Presenter (Part 3) | Informatech CR Blog
    let s see what a mock is and what it can do for us A mock is a fake implementation of an interface or a class which members produce data we already know basically is like making a TV display a TiVO recording instead of an actual live show You know in this example we can know what the data coming from the repository class is just by looking at the code but in the real world we might not have that source code at hand Or even worst that data might come from a production dabatase we don t have access to With a mock we can fake a method to do or return anything we want Our first test is called ItShouldLoadAllClients Since our test naming skills are so incredibly sharp we can imply just by reading that title that a clients list has to be loaded during Presenter class initialization We first create a new method called SetUp that will run right before each time a test method runs to set everything up in this case it will initialize mock instances for the repository class and view interface We then proceed to create an instance of the Presenter class which is the test subject our lab rat yes and then we use the Verify method of the mock that will throw a nasty exception and make the unit test fail miserably if the specified View method LoadClients for this particular case was never called during Presenter initialization using Moq using NUnit Framework using System Collections Generic using System Linq namespace Codenough Demos WinFormsMVP TestFixture public class WhenClientsWindowLoads private Mock IClientsView clientsViewMock private Mock ClientRepository clientsRepositoryMock SetUp public void SetUp this clientsViewMock new Mock IClientsView this clientsRepositoryMock new Mock ClientRepository Test public void ItShouldLoadAllClients Act var clientsPresenter new ClientsPresenter clientsViewMock Object clientsRepositoryMock Object Assert clientsViewMock Verify view view LoadClients It IsAny IList ClientModel Expected clients to be loaded on initialization Of course this test passes A call to the LoadClients method is done at the Presenter constructor The following tests are a little more complicated since we will be setting up methods of the View and repository mocks to return what we need them to return method setup Our next test is ItShouldShowFirstClientOnListDetails which requires our presenter to load the first client on the list after initialization For this case we let the SetUp method do its thing and create the respective mocks and then at our test arrange phase we use the Setup method to make the repository mock return a sample list of clients when the FindAll method is called Finally we verify the LoadClient method of the view was called making this the assertion that makes the test case pass and make us happy or fail and quit our jobs Test public void ItShouldShowFirstClientOnListDetails Arrange var clients new List ClientModel new ClientModel Id 1 Name Matt Dylan Age 28 Gender Male Email mattd none com new ClientModel Id 2 Name Anna Stone Age 22 Gender

    Original URL path: http://blog.informatech.cr/2013/03/21/ui-design-using-model-view-presenter-part-3/ (2015-08-19)
    Open archived version from archive

  • UI Design Using Model-View-Presenter (Part 1) | Informatech CR Blog
    ClientRepository clientsRepository public ClientsForm this clientsRepository new ClientRepository InitializeComponent BindComponent private void InitializeComponent Create and initialize window controls Omitted for brevity private void BindComponent this closeButton Click OnCloseButtonClick this clientsListBox SelectedIndexChanged OnClientsListBoxSelectedIndexChanged this clientsListBox DisplayMember Name this clientsListBox ValueMember Id this clientsListBox DataSource this clientsRepository FindAll private void OnClientsListBoxSelectedIndexChanged object sender EventArgs e var selectedClientId int this clientsListBox SelectedValue var selectedClient this clientsRepository GetById selectedClientId this clientNameTextBox Text selectedClient Name this clientEmailTextBox Text selectedClient Email this clientGenderTextBox Text selectedClient Gender this clientAgeTextBox Text selectedClient Age ToString private void OnCloseButtonClick object sender EventArgs e Application Exit First thing I would like to mention here is that this example satisfies all acceptance criteria you know what it is expected to do we established for the end product It shows the list of clients each time one is selected details of that client are displayed in the details group box and all that magic So what is so bad about this code It does what it should and best of all in roughly 49 lines of code Well as frustrating it might seem something effective is not always efficient The previous piece of code breaks pretty much all aspects of good design Martin Fowler might even shed a little tear just by looking at it Testing What Cannot Be Tested As I mentioned at the beginning of the article unit test code is as important as the actual business source code Always remember that lad Let s define a couple requirements this application needs to satisfy The clients application should as in has to Show all clients in the list box when it loads Show details of the first client in the list when it loads Show details of a client and show it when the user select an item in the clients list box Now let s write test method stubs for these using NUnit Framework namespace Codenough Demos WinFormsMVP TestFixture public class WhenClientsWindowLoads Test public void ItShouldLoadAllClients Test public void ItShouldShowFirstClientOnListDetails Test public void ItShouldShowClientDetailsOnListItemSelected When looking at these tests we can notice they are specific to the presentation portion of the application We are not testing data access the ClientRepository class or rendering related stuff By using the code example provided earlier our tests could fail or pass depending of The repository classes The data coming from the repository The stability of the actual Windows Forms libraries better known as the Please Don t Screw Up Microsoft prayer So we would have to adapt our tests for cases when the ClientsRepository class returns unexpected data or an environment related exception occurs when rendering the window on screen We simply can t perform proper testing of the source code as it is right now At this point code coverage has been compromised not even talk about separation of concerns The ClientForm class does friggin EVERYTHING But fear not Fortunately for us some nerds locked up in a server room under an average temperature of about 5 degrees celcius already encountered themselves

    Original URL path: http://blog.informatech.cr/2013/03/19/ui-design-using-model-view-presenter-part-1/ (2015-08-19)
    Open archived version from archive