Why Developers Should Refactor to Java 8 Immediately




With the release of Java 8 on March 2014, developers where anxious to see the unveiling of the exiting things that the jdk team and the JCP community had put together to make development slightly smooth and exiting for all of us. From an honest point of view Java has been around for a while and its acceptance globally has been a thing of comfort to those of us who have made it our career. From web applications, mobile devices, printers, desktop applications to highly sophisticated mission critical systems, Java has proven indispensable, and extremely competitive to other programming languages in those realms. 

Java Jdk 1.0 was released in 1995, later followed by the release of the famous jdk 5 and jdk 7 in 2011. All of these version came with awesome features that made them worthwhile, but java 8 has come to give Java a permanent place in the world of software development as you will learn from this article. The main things that made the release of Java 8 such a big deal to developers are the following. 

  1. Functional programming (finally).
Imperative programming has always been seen as more error prone, and an enemy of code conciseness and readability as compared to Functional programming. Functional (Declarative) programming as opposed to imperative programming makes code more readable, concise and short, which is very important for developers who write APIs and those consumers products that may need crucial maintenance and upgrades in the future. Java 8 introduces the functional interface found in java. util. function which has a bunch of awesome API such as Function, Predicate and the rest.

The magic without going to great details is described by the following snippet.
    
 Collection. Sort(inventory, new Comparator<Apple>(){
               public int Compare(Apple a1,Apple a2){
                      return a1.getWeight().compareTo(a2.getWeight());
               }
   });

 //This is reduced to 
      inventory.sort(comparing(Apple::getWeight()));

Java 8's  feature for functional programming clearly eliminates writing verbose code and lead to short and more concise, readable code.You just express what you want in a high level manner

     2. Stream processing with the Streams API.

A Stream is a sequence of data items that are conceptually produced one at a time. A program might read items from a stream one by one and similarly write items to an output stream. Java 8 stream API is found in java.util.stream and enables this to be archived. More like database programming handles queries on database tables, the stream API enables data processing in the application layer in more high level declarative manner with no fuss and eliminates complicated algorithms that most programmers have to write just to get the total salary for each employee in a company of 12 employees. An easy way to look at it is using the Unix command line pipe command (|). This operator enables run more than one command concurrently that is each on a separate thread but executing at the same time. Check this out.

                            cat file1 file2 | tr "[A-Z]" "[a-z]" | sort | tail-3
The command above takes two file as streams and converts statements in them to lower case then sorts in ascending order the checks the last 3 lines for output. The beauty of it all is that all of these commands execute concurrently.
We are leaving in a world of multicore processors, so the jdk8 team put this in consideration and final built the Stream API such that it can utilize parallel processing, by transparently running your application on several CPU cores on disjoint parts of the input. This is parallelism almost for free instead of hard work using threads.

An example of a stream operations is the following code. Checking even numbers

private static boolean isPrime(final int number){
       return number > 1 && 
                                IntStream.range(2,number)
                                                .noneMatch(index -> number % index == 8);

}




3.Lambda Expressions

This should have come first on this list; it seems s to be the most effective.
A lambda expression is essentially an anonymous that is un-named function with the symbol ->
Lambda expressions are essentially not executed on their own but are executed together with methods found on a functional interface. A functional interface is really just an interface with a single method, that is the method defines the whole interface. a good example is Runnable which has the function run() and ActionListener which has actionPerformed(ActionEvent event).

Without much lip service, check out the following traditions action listener code that uses anonymous inner classes. 

button.addActionListener(
      new ActionListener(){
            @Override
             public void actionPerformed(ActionEvent event){
                         // event ciode goes here
                          System.out.println("Hello verbose code");
            }
});

// This is dramatically reducing to just one line with lamda expressions.

 button.addActionListener( e ->  System.out.println("Hello Lambda"));

or consider the Runnable interface implementation below

          Thread t = new Thread(
                          new Runnable(){
                                   @Overrride
                                    public void run(){
                                              System.out.println("Hello dumb runnable ");
                                     }
        } );
                   t.start();

//In java 8

                       Thread t2 = new Thread( r -> System.out.println("helloe Runnable lambda");)

4.The new Time API
Java's relationship with date and time has for the most time been really confusing with the release of a cluster of APIs talking of the same thing in very different ways, e.g. Gregorian calendar, java calendar, java Date, sql Date and some others I don’t know of but has no plan of learning since java 8 has solved all that confusion. java. time contains a bunch of really precise specialized classes for dealing with both Date and Time Separately. LocalDate and LocalTime are the most important of all with the abstraction between Date and time finally archived so if I wanted to know what time it was I'd simply say;
                LocalTime rightNow = LocalTime.now();
To get today’s Date;
                LocalDate today = LocalDate.now();
To get a strategic date;
                LocalDate thatDay = LocalDate.of(int year, int month,int dayof Month);
To get difference between today and my birthday in days.
               Period age = Period.between( today,myBithday).toDays();
                //where my birthday would be
                LocalDate myBirthDay = LocalDate.of(1995,Month.January,5);

Tell me this isn't cool!!!!. : ).



5.Other Features

There are so many other incredible feature that come with java 8 some of which surpasses the context of this article but if you are a developer looking towards a much shorter concise, readable, maintainable and bug free/ debug friendly code, then Java 8 holds the key to your programming utopia. I advise that you check out the  official Oracles java 8 documentation or check out this guy’s blog on you tube. An amazing place to get the latest in jdk 8 and probably a flash forward of jdk 9 is the Open jdk site.

In a gif the other features include
  1.  An Enhanced Map interface with Bifurcations.
  2. Passing code to Methods with behavior parameterization
  3. Default Methods
  4. Complitable  future...and many others.
Conclusion
Java 8 is fun and a great tool for any serious developer, but like all tools they can remain to glow and twinkle like stars in the tool box but they are only useful if you apply them in your production code. So make the great migration and refactor you code to java 8 if you have not started java no worries just go only the resources are available and start writing code. For now, I wish you all the best as you explore the wonderful new world of java programming and happy coding. 

Thanks for reading, please feel free to drop your  honest comment or follow this blog to get updates as they arrive.



Comments

Popular posts from this blog

Gradle Declarative Build System

Life Planner Privacy Policy

Python Programming Language