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".
  • Why There Is Interface Pollution in Java 8 | Informatech CR Blog
    arithmetic on boxed ops sucks and having no story for reducing over ints would be terrible So we re in a tough corner and we re trying to not make it worse Trick 1 for not making it worse is we re not doing all eight primitive types We re doing int long and double all the others could be simulated by these Arguably we could get rid of int too but we don t think most Java developers are ready for that Yes there will be calls for Character and the answer is stick it in an int Each specialization is projected to 100K to the JRE footprint Trick 2 is we re using primitive streams to expose things that are best done in the primitive domain sorting reduction but not trying to duplicate everything you can do in the boxed domain For example there s no IntStream into as Aleksey points out If there were the next question s would be Where is IntCollection IntArrayList IntConcurrentSkipListMap The intention is many streams may start as reference streams and end up as primitive streams but not vice versa That s OK and that reduces the number of conversions needed e g no overload of map for int T no specialization of Function for int T etc We can see that this was a difficult decision for the expert group I think few would agree that this is cool and most of us would most likely agree it was necessary The Checked Exceptions Issue There was a third driving force that could have made things even worse and it is the fact that Java supports two type of exceptions checked and unchecked The compiler requires that we handle or explicitly declare checked exceptions but it requires nothing for unchecked ones So this creates an interesting problem because the method signatures of most of the functional interfaces do not declare to throw any exceptions So for instance this is not possible Writer out new StringWriter Consumer String printer s out write s oops compiler error It cannot be done because the write operation throws a checked exception i e IOException but the signature of the Consumer method does not declare it throws any exception at all So the only solution to this problem would have been to create even more interfaces some declaring exceptions and some not or come up with yet another mechanism at the language level for exception transparency Again to make things less worse the expert group decided to do nothing in this case In the words of Brian Goetz in the lambda mailing list Yes you d have to provide your own exceptional SAMs But then lambda conversion would work fine with them The EG discussed additional language and library support for this problem and in the end felt that this was a bad cost benefit tradeoff Library based solutions cause a 2x explosion in SAM types exceptional vs not which interact badly with existing combinatorial explosions for

    Original URL path: http://blog.informatech.cr/2014/04/04/jdk-8-interface-pollution/?replytocom=2537 (2015-08-19)
    Open archived version from archive


  • Why There Is Interface Pollution in Java 8 | Informatech CR Blog
    on boxed ops sucks and having no story for reducing over ints would be terrible So we re in a tough corner and we re trying to not make it worse Trick 1 for not making it worse is we re not doing all eight primitive types We re doing int long and double all the others could be simulated by these Arguably we could get rid of int too but we don t think most Java developers are ready for that Yes there will be calls for Character and the answer is stick it in an int Each specialization is projected to 100K to the JRE footprint Trick 2 is we re using primitive streams to expose things that are best done in the primitive domain sorting reduction but not trying to duplicate everything you can do in the boxed domain For example there s no IntStream into as Aleksey points out If there were the next question s would be Where is IntCollection IntArrayList IntConcurrentSkipListMap The intention is many streams may start as reference streams and end up as primitive streams but not vice versa That s OK and that reduces the number of conversions needed e g no overload of map for int T no specialization of Function for int T etc We can see that this was a difficult decision for the expert group I think few would agree that this is cool and most of us would most likely agree it was necessary The Checked Exceptions Issue There was a third driving force that could have made things even worse and it is the fact that Java supports two type of exceptions checked and unchecked The compiler requires that we handle or explicitly declare checked exceptions but it requires nothing for unchecked ones So this creates an interesting problem because the method signatures of most of the functional interfaces do not declare to throw any exceptions So for instance this is not possible Writer out new StringWriter Consumer String printer s out write s oops compiler error It cannot be done because the write operation throws a checked exception i e IOException but the signature of the Consumer method does not declare it throws any exception at all So the only solution to this problem would have been to create even more interfaces some declaring exceptions and some not or come up with yet another mechanism at the language level for exception transparency Again to make things less worse the expert group decided to do nothing in this case In the words of Brian Goetz in the lambda mailing list Yes you d have to provide your own exceptional SAMs But then lambda conversion would work fine with them The EG discussed additional language and library support for this problem and in the end felt that this was a bad cost benefit tradeoff Library based solutions cause a 2x explosion in SAM types exceptional vs not which interact badly with existing combinatorial explosions for primitive

    Original URL path: http://blog.informatech.cr/2014/04/04/jdk-8-interface-pollution/?replytocom=2536 (2015-08-19)
    Open archived version from archive

  • Functional Programming with Java 8 Functions | Informatech CR Blog
    3 Now naively we could invoke this two functions together to increment and multiply a number by 3 right Like this Integer x 10 Integer res mul3 apply add1 apply x yields 33 But what if we created a function that did both things instead Consider the following pseudocode f g x g f x This would be a function that takes two other unary functions and creates yet another function that applies the original two in certain order This is a classical example of what is called function composition In some languages there is even an operator to compose two functions in this way h f o g Where o would be a binary operator that would compose functions f and g pretty much as we did in pseudocode above and produce a new function h How can we do function composition in Java I can think of two ways to do this in Java one more difficult than the other Let s start with the more difficult first because that will let us appreciate the value of the simpler solution later on Function Composition Strategy 1 First we must start by realizing that the function in pseudocode above is a binary function i e a function that receives two arguments But all our examples so far have dealt only with unary functions It would seem this is not important but in Java it is since functions of different arities have different target functional interfaces In Java a function that receives two arguments is called BinaryOperator For instance using a BinaryOperator we could implement a sum operator BinaryOperator Integer sum a b a b Integer res sum apply 1 2 yields 3 Well just as easily we could implement the compose operator right Only that in this case instead of two simple integers we receive two unary functions BinaryOperator Function Integer Integer compose compose f g x g apply f apply x Now we can easily use this to fabricate a compound function that adds 1 and multiplies by 3 one after the other Function Integer Integer h compose apply add1 mul3 Integer res h apply 10 yields 33 And now we can beautifully and in really simple way combine two unary integer functions Function Composition Strategy 2 Now function composition is something so common that it would have been a mistake if the Java Expert Group would have not considered it in their API design and so to make our lives simpler all Function objects have a method called compose that allows us to very easily compose two functions together The following code produces the exact same result as above Function Integer Integer h mul3 compose add1 Integer res h apply 10 Partial Function Application or Currying In most functional programming languages it is possible to create partially applied functions That is if a function is receiving multiple arguments we can partially invoke the function providing just a few arguments and receive a partially applied function out of

    Original URL path: http://blog.informatech.cr/2014/10/19/functional-programming-with-java-8-functions/?shared=email&msg=fail (2015-08-19)
    Open archived version from archive

  • JSApps 101: AngularJS In A Nutshell | Informatech CR Blog
    of the user interface Create and include a JavaScript file where we are going to create our application object wait for it and define some controllers Add scope almost there variables and functions that will be bound to the view through special AngularJS HTML attributes Basic View Markup Let s start this in a natural way let s create the user interface first We will create a file called todolist html and we will add the following HTML to it Now nothing fancy right there we just included the AngularJS library at line 8 and another file at line 9 which we will create in a moment However just notice the structure of the document We have an UL element which will represent our list of to do items and then a couple input controls so we can add new items to the list It does not have any information on it for now but eventually it will And it will be awesome Let s leave this code as it is for now let s move to the app js file which has all the fun going on Adding Logic The Controller Just by looking at the previous HTML document you will realize that there are two things we need regarding to view state data An array to store the to do items to be displayed in the UL element at line 13 A function to add new items when I click the Add button at line 15 Simple right Well let s create a new file called app js and add the following code I ll explain it later First things first let s take a look at line 1 Before we start building controllers that handle UI logic we need to create what is known as an AngularJS application module this is done by calling the angular module function and passing it the module name which returns the created module This object will later be used as a container where you will store all of the controllers belonging to this particular JS App The variable angular is available after we included the AngularJS library in our HTML document at line 8 After we create the application object we can start creating controllers being done in line 3 through the controller function which is now callable from the application module we created in line 1 This function takes two arguments the name of the controller and a callback function that will be responsible of initializing the controller and which will be called each time a controller is instantiated by AngularJS AngularJS also passes a special variable to that function called scope everything that is added to the scope variable during controller initialization will be accessible to the view for data binding better said it represents what the view can see The rest of the lines are quite self explanatory Lines 7 to 11 adds a pre initialized array of to do items to the scope that will be used as storage for new items It represents the items that will be displayed in the empty UL element we have right now Line 13 declares a variable that will hold the description of new items to be added after the Add button is clicked Lines 17 to 21 define a function that will add new items to the to do items array this should be called each time the Add button is clicked Binding The View Now that we have AngularJS the application module and the to do list controller we are ready to start binding HTML elements in the view to the scope But before that we need to change our html tag a little and add some special AngularJS attributes Notice the ng app attribute we added to the html tag this is your first contact with one of the several directives that are part of the AngularJS data binding framework Directives are simply HTML element markers that are to be processed by the data binding engine What does ng app do Well it tells AngularJS which application module it should use for this HTML document you might notice we specified ToDoListApp which is the one we created in out app js file at line 1 After we associate our HTML document with the ToDoListApp second step is to specify a controller for our view this is done through the ng controller directive The ng controller directive assigns a controller to a section of the HTML document in other words this is how we tell Angular where a view starts and when it ends Anyways modify the body tag so it looks like this Same with the ng app directive the previous code tells AngularJS that everything inside the body tag will be governed by the ToDoListController which we created in our app js file at line 3 Now we are ready to start binding elements to members added to the scope variable during the ToDoListController controller initialization The ng repeat Directive Let s start with the empty UL list element In this case we want to create a new child LI element per item that is contained in the to do items array Let s use the ng repeat directive for this matter add the following code inside the UL tags OK hold on tight The ng repeat directive will repeat an element per item in an array used as data source the quoted value represents the iterator expression which defines the array to be iterated and an alias used to refer the current item being iterated In this case we specified that it should repeat the LI element for all of the items in the items array defined in the scope variable from line 7 through 11 in the app js file Lastly inside the LI tags we define an Angular template which is an expression enclosed in double curly braces that will be compiled dynamically during run time In this case the template is extracting

    Original URL path: http://blog.informatech.cr/2014/04/15/jsapps-101-angular-js/?replytocom=2461 (2015-08-19)
    Open archived version from archive

  • JSApps 101: AngularJS In A Nutshell | Informatech CR Blog
    the user interface Create and include a JavaScript file where we are going to create our application object wait for it and define some controllers Add scope almost there variables and functions that will be bound to the view through special AngularJS HTML attributes Basic View Markup Let s start this in a natural way let s create the user interface first We will create a file called todolist html and we will add the following HTML to it Now nothing fancy right there we just included the AngularJS library at line 8 and another file at line 9 which we will create in a moment However just notice the structure of the document We have an UL element which will represent our list of to do items and then a couple input controls so we can add new items to the list It does not have any information on it for now but eventually it will And it will be awesome Let s leave this code as it is for now let s move to the app js file which has all the fun going on Adding Logic The Controller Just by looking at the previous HTML document you will realize that there are two things we need regarding to view state data An array to store the to do items to be displayed in the UL element at line 13 A function to add new items when I click the Add button at line 15 Simple right Well let s create a new file called app js and add the following code I ll explain it later First things first let s take a look at line 1 Before we start building controllers that handle UI logic we need to create what is known as an AngularJS application module this is done by calling the angular module function and passing it the module name which returns the created module This object will later be used as a container where you will store all of the controllers belonging to this particular JS App The variable angular is available after we included the AngularJS library in our HTML document at line 8 After we create the application object we can start creating controllers being done in line 3 through the controller function which is now callable from the application module we created in line 1 This function takes two arguments the name of the controller and a callback function that will be responsible of initializing the controller and which will be called each time a controller is instantiated by AngularJS AngularJS also passes a special variable to that function called scope everything that is added to the scope variable during controller initialization will be accessible to the view for data binding better said it represents what the view can see The rest of the lines are quite self explanatory Lines 7 to 11 adds a pre initialized array of to do items to the scope that will be used as storage for new items It represents the items that will be displayed in the empty UL element we have right now Line 13 declares a variable that will hold the description of new items to be added after the Add button is clicked Lines 17 to 21 define a function that will add new items to the to do items array this should be called each time the Add button is clicked Binding The View Now that we have AngularJS the application module and the to do list controller we are ready to start binding HTML elements in the view to the scope But before that we need to change our html tag a little and add some special AngularJS attributes Notice the ng app attribute we added to the html tag this is your first contact with one of the several directives that are part of the AngularJS data binding framework Directives are simply HTML element markers that are to be processed by the data binding engine What does ng app do Well it tells AngularJS which application module it should use for this HTML document you might notice we specified ToDoListApp which is the one we created in out app js file at line 1 After we associate our HTML document with the ToDoListApp second step is to specify a controller for our view this is done through the ng controller directive The ng controller directive assigns a controller to a section of the HTML document in other words this is how we tell Angular where a view starts and when it ends Anyways modify the body tag so it looks like this Same with the ng app directive the previous code tells AngularJS that everything inside the body tag will be governed by the ToDoListController which we created in our app js file at line 3 Now we are ready to start binding elements to members added to the scope variable during the ToDoListController controller initialization The ng repeat Directive Let s start with the empty UL list element In this case we want to create a new child LI element per item that is contained in the to do items array Let s use the ng repeat directive for this matter add the following code inside the UL tags OK hold on tight The ng repeat directive will repeat an element per item in an array used as data source the quoted value represents the iterator expression which defines the array to be iterated and an alias used to refer the current item being iterated In this case we specified that it should repeat the LI element for all of the items in the items array defined in the scope variable from line 7 through 11 in the app js file Lastly inside the LI tags we define an Angular template which is an expression enclosed in double curly braces that will be compiled dynamically during run time In this case the template is extracting a

    Original URL path: http://blog.informatech.cr/2014/04/15/jsapps-101-angular-js/?shared=email&msg=fail (2015-08-19)
    Open archived version from archive

  • Improving Code With Fluent Interfaces | Informatech CR Blog
    createTaskFor method in the main method without having to reference the Task class at all on it making our fluent interface totally unobtrusive What a good boy Now our main method looks a little something like this package com codenough demos fluentthreads import static com codenough demos fluentthreads threading Task import com codenough demos fluentthreads threading public class Main public static void main String args throws Exception System out println Creating task Task task createTaskFor new Action Override public void onExecute try Thread sleep 5000 System out println Task internal action execution finished catch InterruptedException exception throw new Error Thread sleep was interrupted exception onErrorUse new ErrorHandler Override public void onErrorCaught Exception exception System out println An error ocurred while executing task internal action thenExecute System out println Task created Now running while true Thread sleep 1000 if task isRunning System out println Still waiting for task else break System out println Task execution completed Benefits Fluent interfaces leverage existing language features which are not that user friendly to improve code readability This allows us to produce awesome code with superior quality since is a lot easier to read understand and maintain QAs will be grateful which is good Of course additional code and effort is required to implement fluent interfaces but in the end it all pays when we for example have to implement additional features or modify existing code in a codebase we might have last touched ages ago You ll save thousands of dollars on aspirin tablets Example FluentThreads Example Further Reading FluentInterface by Martin Fowler Share this Email Facebook Twitter Like this Like Loading Related March 22 2013 by Luis Aguilar Categories Java Programming Tags fluent interfaces good practices java 4 Comments Post navigation Programmer Jokes Java Streams Preview vs Net High Order Programming with LINQ 4 thoughts on Improving Code With Fluent Interfaces Edwin Dalorzo says March 22 2013 at 3 27 pm Quite interesting above all because I was not familiar with the name I was familiar with the concept of method chaining and I have seen it many times when we use a Builder pattern where this is very common but I was not familiar with Martin Fowler s coined name Do you have a reference for this I would be great to read Martin s article as well I have to say that I personally would have preferred an example that had nothing to do with threads because the multithreading may deviate the attention from the actual beauty of the post which is the power of fluent interfaces and I think that if us the readers wouldn t have to consider the multithreading side of the story the examples would be simpler and more enlightening For example I have several comments about threading issues in the examples that have nothing to do with the main idea of the post My comments do not undermine the power of fluent interfaces but they do question some unconsidered multithreading scenarios in the examples For instance

    Original URL path: http://blog.informatech.cr/2013/03/22/improving-code-with-fluent-interfaces/ (2015-08-19)
    Open archived version from archive

  • fluent interfaces | Informatech CR Blog
    operation is still running After the operation completes we print a message saying it so Quite useless application we have here but will help demonstrate our example Traditionally we would have some code like this to achieve what we want package com codenough demos fluentthreads public class Main private static Boolean operationThreadIsRunning false public static void main String args throws Exception setOperationStatus false System out println Creating thread Runnable runnableOperation new Runnable Override public void run setOperationStatus true try Thread sleep 5000 System out println Operation execution finished catch Exception e System out println An error ocurred while executing operation setOperationStatus false Thread operationThread new Thread runnableOperation operationThread start System out println quot Thread created Now running quot while true Thread sleep 1000 if operationThreadIsRunning System out println Still waiting for thread else break System out println Thread execution completed public static void setOperationStatus Boolean isRunning operationThreadIsRunning isRunning Again this code does is just fine But someone with limited knowledge of Java or programming at all would have a hard time trying to figure out what the hell is a Thread or Runnable Let alone Override So for the sake of easy readability we can modify the code structure a little bit so instead of creating threads and runnables we can do something like this createTaskFor new Action Override public void onExecute Long running operation onErrorUse new ErrorHandler Override public void onErrorCaught Exception exception Handle errors thenExecute Much better huh Now readers should only worry about guessing what the friendly Override annotations are for Behind The Scenes This lovely syntax is possible thanks to a wrapper class working behind the scenes called Task which is full o chained methods which return its own instance so we can keep calling and calling methods like there s no tomorrow until we are ready to run the actual task by calling the thenExecute method All for the sake of syntactic sugar Here is the implementation of the Task class package com codenough demos fluentthreads threading public class Task private Boolean isRunning private ErrorAction errorAction private final Action action public Task Action action this action action this isRunning false public Boolean isRunning return this isRunning public Task onErrorUse ErrorAction errorAction this errorAction errorAction return this public Task thenExecute Runnable runnableAction new Runnable Override public void run try isRunning true action onExecute isRunning false catch Exception exception errorAction onErrorCaught exception new Thread runnableAction start return this public static Task createTaskFor Action action return new Task action As you might notice on most methods they return their own class instance These are chained methods and in this case are used to configure the task I have taken advantage of Java static imports so I can call the createTaskFor method in the main method without having to reference the Task class at all on it making our fluent interface totally unobtrusive What a good boy Now our main method looks a little something like this package com codenough demos fluentthreads import static com codenough demos fluentthreads threading

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

  • Luis Aguilar | Informatech CR Blog | Page 2
    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 testing is SO important

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