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".
  • UI Design Using Model-View-Presenter (Part 2) | Informatech CR Blog
    public interface IClientsView event Action ClientSelected event Action Closed IList ClientModel Clients get ClientModel SelectedClient get void LoadClients IList ClientModel clients void LoadClient ClientModel client The interface only defines the methods needed by the Presenter so it can puppet it as needed in order to get its data and validate anything before it gets back into the database or any other event triggered by the user Also see those fancy events on the view interface Dude I didn t even knew interfaces could have events on it LOL just kidding Actually they are there so the Presenter subscribe to them and then the View can fire them to notify of data changes Is a two way communication Okay now to complete the View portion we need to create the concrete implementation of the view interface In this case is our old Windows Forms class which has gone under a strict diet low on carbs to reduce its functionality to the minimum using System using System Collections Generic using System Windows Forms namespace Codenough Demos WinFormsMVP public partial class ClientsForm Form IClientsView public event Action ClientSelected public event Action Closed public ClientsForm this InitializeComponent this BindComponent public IList ClientModel Clients get return this clientsListBox DataSource as IList ClientModel public ClientModel SelectedClient get return this clientsListBox SelectedItem as ClientModel public void LoadClients IList ClientModel clients this clientsListBox DataSource clients public void LoadClient ClientModel client this clientNameTextBox Text client Name this clientEmailTextBox Text client Email this clientGenderTextBox Text client Gender this clientAgeTextBox Text client Age ToString private void BindComponent this closeButton Click OnCloseButtonClick this clientsListBox DisplayMember Name this clientsListBox SelectedIndexChanged OnClientsListBoxSelectedIndexChanged private void OnClientsListBoxSelectedIndexChanged object sender EventArgs e if this ClientSelected null this ClientSelected private void OnCloseButtonClick object sender EventArgs e if this Closed null this Closed Now the View implementation only loads data from someone else and fires events as the loaded data changes so anyone out there in space listening to it be aware of the changes and will take appropriate action OK that sounded like a line from a Law Order episode As you might have already guessed the only component aware of the View events would be the Presenter So the next step is to implement the infamous Presenter class The Presenter is a component that is aware of what is happening in the View through its events See what I said about repeating myself But hopefully that will help get things carved out in your head bud As we mentioned before the Presenter talks to the View by using its interface instead of the concrete implementation the ClientsForm class that is this for the sake of code testability Later on we are going to provide the Presenter with a mock instead of the actual View implementation We are going to learn what a mock is later no need to hurry using System Linq namespace Codenough Demos WinFormsMVP public class ClientsPresenter private readonly IClientsView view private readonly ClientRepository clientsRepository public ClientsPresenter IClientsView view ClientRepository clientsRepository this view view this

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


  • model view presenter | Informatech CR Blog
    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 ALL At least not at first since you have to think on all the possible test scenarios your code could go through But in the long term this is what makes testable code more robust and clean than regular hastily thrown together code Okay this makes it up for it Hope you enjoyed it and learned a couple things Stay tuned for more talk on patterns and good practices and maybe really off topic things Oh Don t forget to check out the code examples including an exciting port on Java Code Examples WinformsMVP C SwingMVP Java Share this Email Facebook Twitter Like this Like Loading March 21 2013 by Luis Aguilar Categories NET Programming Tags net c development model view presenter mvp user interface design 1 Comment UI Design Using Model View Presenter Part 2 What Just Happened In the previous part we demonstrated the traditional way of doing things when it comes to UI design We also reviewed some key concepts like Code Coverage and Separation Of Concerns Lastly we reviewed some concepts behind the Model View Presenter pattern Yeap that was a lot of stuff So if you haven t read it yet be a good boy and go read it now Everything has been really theoric up until now which is boring to depressing levels But don t worry I ll make it up for you on this part We are now going to look at how each piece of the pattern is implemented Alright let s move on then but have in mind this diagram at all times UI Design Redemption Ok time to make things right First thing to do to sort this mess up dear reader is to create the Model The Model is a domain object fancy name for a class full of properties only which contains the information the View is gonna show In this case our View will contain a list of clients so the Model is actually the Client class renamed to obey naming conventions as ClientModel C mon lots of

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

  • mvp | Informatech CR Blog
    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 ALL At least not at first since you have to think on all the possible test scenarios your code could go through But in the long term this is what makes testable code more robust and clean than regular hastily thrown together code Okay this makes it up for it Hope you enjoyed it and learned a couple things Stay tuned for more talk on patterns and good practices and maybe really off topic things Oh Don t forget to check out the code examples including an exciting port on Java Code Examples WinformsMVP C SwingMVP Java Share this Email Facebook Twitter Like this Like Loading March 21 2013 by Luis Aguilar Categories NET Programming Tags net c development model view presenter mvp user interface design 1 Comment UI Design Using Model View Presenter Part 2 What Just Happened In the previous part we demonstrated the traditional way of doing things when it comes to UI design We also reviewed some key concepts like Code Coverage and Separation Of Concerns Lastly we reviewed some concepts behind the Model View Presenter pattern Yeap that was a lot of stuff So if you haven t read it yet be a good boy and go read it now Everything has been really theoric up until now which is boring to depressing levels But don t worry I ll make it up for you on this part We are now going to look at how each piece of the pattern is implemented Alright let s move on then but have in mind this diagram at all times UI Design Redemption Ok time to make things right First thing to do to sort this mess up dear reader is to create the Model The Model is a domain object fancy name for a class full of properties only which contains the information the View is gonna show In this case our View will contain a list of clients so the Model is actually the Client class renamed to obey naming conventions as ClientModel C mon lots of people

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

  • user interface design | Informatech CR Blog
    bear with me here the Model is a really simple class composed only of properties better known as plain old C object or POCO for the friends Wait poco actually means not much in Spanish so it does not much Wow cool right Okay here is a list of things the Model should NOT do Do any data validation Refresh save or update its data on the database Throw exceptions like it was something actually funny Be aware of any other class outside the domain model Provide a solution to world hunger actually that would be pretty impressive but DON T Next step is to create an interface that will serve as a contract of whatever the View is capable to do so the Presenter is aware of it Remember it will be communicating with it to serve view data and receive input so the guy needs to know what is in the view regardless of implementation using System using System Collections Generic namespace Codenough Demos WinFormsMVP public interface IClientsView event Action ClientSelected event Action Closed IList ClientModel Clients get ClientModel SelectedClient get void LoadClients IList ClientModel clients void LoadClient ClientModel client The interface only defines the methods needed by the Presenter so it can puppet it as needed in order to get its data and validate anything before it gets back into the database or any other event triggered by the user Also see those fancy events on the view interface Dude I didn t even knew interfaces could have events on it LOL just kidding Actually they are there so the Presenter subscribe to them and then the View can fire them to notify of data changes Is a two way communication Okay now to complete the View portion we need to create the concrete implementation of the view interface In this case is our old Windows Forms class which has gone under a strict diet low on carbs to reduce its functionality to the minimum using System using System Collections Generic using System Windows Forms namespace Codenough Demos WinFormsMVP public partial class ClientsForm Form IClientsView public event Action ClientSelected public event Action Closed public ClientsForm this InitializeComponent this BindComponent public IList ClientModel Clients get return this clientsListBox DataSource as IList ClientModel public ClientModel SelectedClient get return this clientsListBox SelectedItem as ClientModel public void LoadClients IList ClientModel clients this clientsListBox DataSource clients public void LoadClient ClientModel client this clientNameTextBox Text client Name this clientEmailTextBox Text client Email this clientGenderTextBox Text client Gender this clientAgeTextBox Text client Age ToString private void BindComponent this closeButton Click OnCloseButtonClick this clientsListBox DisplayMember Name this clientsListBox SelectedIndexChanged OnClientsListBoxSelectedIndexChanged private void OnClientsListBoxSelectedIndexChanged object sender EventArgs e if this ClientSelected null this ClientSelected private void OnCloseButtonClick object sender EventArgs e if this Closed null this Closed Now the View implementation only loads data from someone else and fires events as the loaded data changes so anyone out there in space listening to it be aware of the changes and will take appropriate action OK that sounded like a line from a Law Order episode As you might have already guessed the only component aware of the View events would be the Presenter So the next step is to implement the infamous Presenter class The Presenter is a component that is aware of what is happening in the View through its events See what I said about repeating myself But hopefully that will help get things carved out in your head bud As we mentioned before the Presenter talks to the View by using its interface instead of the concrete implementation the ClientsForm class that is this for the sake of code testability Later on we are going to provide the Presenter with a mock instead of the actual View implementation We are going to learn what a mock is later no need to hurry using System Linq namespace Codenough Demos WinFormsMVP public class ClientsPresenter private readonly IClientsView view private readonly ClientRepository clientsRepository public ClientsPresenter IClientsView view ClientRepository clientsRepository this view view this clientsRepository clientsRepository var clients clientsRepository FindAll this view ClientSelected OnClientSelected this view LoadClients clients if clients null this view LoadClient clients First public void OnClientSelected if this view SelectedClient null var id this view SelectedClient Id var client this clientsRepository GetById id this view LoadClient client This time around the one handling data access through the repository class is the Presenter The View is no longer aware of where its data is coming from that s a good thing Also we can notice how the Presenter reacts each time a client is selected on the list box since it has subscribed to the View s ClientSelected event Fancy right Now the only thing left to do is to wire up everything so we can run this incredibly clever application which will save many companies from bankruptcy from now on to the future Of course that is for the next part in our series Gotcha huh Coming Up In our next part we will wire up all this mess so we have a nice and working application We will also implement all unit tests we defined in the first part Is going to be lots of fun I promise Go read Part 3 Share this Email Facebook Twitter Like this Like Loading March 20 2013 by Luis Aguilar Categories NET Programming Tags net c development model view presenter mvp user interface design 4 Comments UI Design Using Model View Presenter Part 1 Introduction Current tendencies and best practices in software development lead to the common pattern that a software system has to be solid scalable and reliable In order to comply with those three requirements two aspects have to be considered during design phase Code coverage and separation of concerns What Ok so code coverage is a metric that indicates how much of the code is being covered by unit tests or in other words English plz how testable is the source code we have written during those lovely 18 hour shifts Yes unit

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

  • good practices | Informatech CR Blog
    unit tests or in other words English plz how testable is the source code we have written during those lovely 18 hour shifts Yes unit testing is SO important it has its own goddamn metric Then we have separation of concerns which plays close with code coverage since in order to have handsome unit tests we need to give each component of the system a single concern to deal with In software design the milk man cannot deliver newspapers around the neighborhood Each component has a specific well defined responsibility and it has to stick to that scope But what does all of this has to do with user interface design Well user interface code is the number one culprit of most software design flaws since it often lead developers into breaking these two design aspects specifically Is a common well known scenario where a class that represents a window to be rendered on screen also performs business logic validations and queries the database directly This not only screws up the whole idea of separation of concerns but also makes unit testing of that particular class almost impossible punching code coverage right in the face That s right Developers are well known for not being too skilled at designing pretty GUIs However when they nail it they screw infrastructure up Go figure Anyways this three part series of articles intend to demonstrate clear examples of both the traditional way and the awesome way don t mind quotes at all using the Model View Presenter pattern in order to improve overall infrastructure design of the application user interface Examples will be provided in C using Windows Forms The example application is Mono compliant so it can be compiled to run in several platforms using the Mono Framework An additional version for Java using Swing will be provided at the last article of the series The Scenario For our practical example we are going to build a small application that displays a list of clients available in a data source to the user on screen The user will then be able to select clients from the list and view additional details like age gender and e mail address You get the idea The clients will be queried from a repository which for matters of simplicity I m just THAT lazy will return data from a pre defined generic list For a start here is the repo source code using System Collections Generic namespace Codenough Demos WinFormsMVP public class ClientRepository private IList Client clients new List Client new Client Id 1 Name Matt Dylan Age 28 Gender Male Email mattd none com new Client Id 2 Name Anna Stone Age 22 Gender Female Email ann none com public virtual Client GetById int id foreach Client client in this clients if client Id id return client return null public virtual IList FindAll return this clients Traditional UI Design Read Effective Not Efficient Traditional ways to develop user interfaces tend to give all responsibility to

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

  • Memoized Fibonacci Numbers with Java 8 | Informatech CR Blog
    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 Related May 8 2013 by Edwin Dalorzo Categories Java Tags fibonacci java 7 Comments About Edwin Dalorzo Software Engineer View all posts by Edwin Dalorzo Post navigation Java 8 Optional Objects 6 Days with Windows Phone 7 thoughts on Memoized Fibonacci Numbers with Java 8 Caesar Ralf Franz Hoppen says May 13 2013 at 10 45

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

  • fibonacci | Informatech CR Blog
    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

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

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

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