Dealing with the new Java Release Schedule

Oracle has just announced that the End of Support for Java 8 is going to be January 2019. This, in turn, means that every business using Java will need to upgrade for security reasons to the latest version of Java. The new release strategy says that newer versions have a 6-month support and then a new major version of Java is going to be released. In Addition, they are changing the Version naming scheme from SemVer to <year>.<month>Basically allowing Oracle to introduce breaking changes to Java every 6 months. As a business you basically are given the choice:

1. Upgrade Java every 6 Months

If we would go with the first option it already gets strange. At the moment assuming you are currently on Java 8 you would need to directly update to Java 10, as Java 9 Support already has ended. However, you still would first need to update to Java 9 just to see what all does not work anymore due to Java 9 major changes and then move to Java 10. But that is assuming that your 3rd Party libraries also already did the update to the new version. Then in September, you would upgrade to Java 11. A lot of people are going to say, well good then we just do not upgrade now and wait for September to do the upgrade. Yes, you can do that, but that does not really matter as in the following March you anyway would have to upgrade again. Your business needs a new strategy how to deal with the rapid version changes. That is now only supported for 6 months instead of the ~3+ years. Personally, I really like this, as most businesses have the strategy: “Version upgrade? only when hell freezes over” – that only costs money and has no immediate benefits.  Focusing on the short-term impact, neglecting the fact that continuous upgrades are cheaper in the long-term and contain less risk compared to the big bang upgrades. Source: Java Release Roadmap

2. Get Java Advanced licenses (Extended Support)

The alternative is to just get the Java Advanced license. I could not find any information on the Oracle site. Basically, you are paying around 500usd/core (Source), so depending on how many servers you are using you will have to pay a small fortune. At the same time, you are only sidestepping the upgrade issue as you anyway have to upgrade your system every 3 years at least once.

3. Use another Language

Depending on your codebase you may want to look into moving away from Java. If you are starting a project you may want to look into C#, Python or JavaScript (or any other language) Many Java projects are anyway already running for 15+ years and may need a technological overhaul. You could think about switching to micro-services and start replacing a service one by one with another technology. While there are many costs and risks involved switching technologies, *developer training, system stability, continuous support etc. etc.

Conclusion

It really depends on your project and how your business deals with change how you ultimately deal with Release Schedule.  You definitely need a strategy how to approach this problem. The future of Java is unclear. Oracle is promising more rapid improvements of the language.  But there is the possibility that the changes are too drastic so that businesses will stop using the language. Either Java will continue to be one of the most used programming languages or fade into obscurity. The only thing that is certain is that the world of Java is going to be changing significantly in the next couple of years.

JSP: Passing Variable Data to JavaScript

When you try to marry old JSP Technology with the modern wonders of Typescript/ES6. You will want to expose some data provided by the backend into the JavaScript. If you have the possibility you would use a fetch()call to receive JSON. Sometimes, it is not possible to do a big rewrite of the JSP to fix a minor bug. Here is a very dirty way to pass data from the JSP into the JS code. This code will utilize the HTML5 data-attribute. Learn more about it here

JSP File:

<fmt:message var="someText" key="core.someText" />

<div id="jsVariables"
     data-someText="${self.someText}"
    >
</div>

JavaScript:

let dataContainer = document.getElementById('jsVariables');
let someText = dataContainer.dataset.someText;

JQuery:

let someText = $('#jsVariables').data('someText')

This is a very elegant solution (for well I guess using JSPs), now you can run ESLint on your Javascript Code and will not have any unresolved variables.

Notes on MITx: 6.005.1x Software Construction in Java (Week 2)

This week the course is covering another two very important topics: Testing and Specifications.

LECTURE 3: Testing

Testing is a very important part of creating functionally correct programs.

Testing will be always incomplete

You will try to test your program using three methods:

  1. Formal Reasoning, essentially you manually verify that your program works correctly
  2. Code Review: Another Programmer takes a look and says everything is ok.
  3. Test Suites: Essentially you write another program (which can have its own bugs) to test your program. You define the inputs and the expected output and compare them.

The course mentions again the residual defect rates of 1-10 defects/kloc(1000 lines of code). Again this does not cite where this number actually comes from. Especially when using Industry Standards and Test Suites this high number would drastically drop to a much lower number. However, in the end, it only would remain to be an assumption since the actual number cannot be determined. You testing your program for every possible input (Exhaustive testing) is not feasible. The strategy to simply take a look and see if it works (Haphazard testing) will also not reveal all bugs. The same is true for “Random” testing. All of these test methods cannot be used to test software.

Write Tests

When you are writing tests you should think about how you can make your program fail. Test drive development takes the following approach.

  1. Specify what you want to program
  2. Write tests that would test the specification
  3. Write code so that your code passes the tests

The specification is key to define what inputs are possible and which outputs will be produced. (This also includes throwing errors) Blackbox testing only focuses on the input and output of the function. These tests do not take into account how the algorithm actually works. The alternative is Whitebox testing takes into account how the program is implemented.

Test Coverage

Now that you have written tests for all of your code, did you also test all of your code? Coverage takes a look at if all Statements and all possible paths through your code are covered. There are various Code coverage tools available that you can run and then visually see which part of the code is covered by your tests. In reality, you should try to achieve a coverage of 70-90% of your code achieving 100% is usually not possible due to time constraints. Of course, this is not the case if you are using Test Driven Development.

Running Tests

Usually, you would create a testsuite of Unit Tests. You should integrate these tests into your build process to ensure that the tests run automatically. Especially when you modify existing code this will ensure that your modifications will not accidentally break something unintentionally. When working with multiple people you should add hooks to your git repository that it rejects code that does not pass your test suite.

LECTURE 4: Specifications

This lecture is going to cover preconditions and post-conditions in method specifications, and how to write correct specifications.

What is a specification?

The lecture defines a specification primarily only concerning how the interfaces are defined and how the specification document essentially is used as a communication device to talk to the client. Now, this actually assumes that the client is another programmer that wants the module/system to do a specific functionality. In my work experience usually, the client has no technical background and expects the programmer to know what he wants.  Yes, the specification is the key document on how to negotiate which features etc. the client requires, it is however not exactly defined which functions or how interfaces should be created, this is usually the task of the programmer. The course actually is more talking about a documentation document how and which interfaces exist in the code you are programming for the client. The documentation is key whenever other programmers need to use the code you have programmed. In either case, the specification document is a key document. It defines the work that needs to be done. The document shields the programmer from the client, if the client forgot to specify something, thus the programmer did not implement it he can prove it was the client’s fault. At the same time, the programmer is bound to the document that he actually implements all features. (or negotiates, talks with the client that the functionality is unfeasible, or not possible to be implemented)

Pre and Post Conditions

For each function, you require the preconditions (what inputs) and postconditions (what outputs). The inputs may have to have a specific structure, cannot be a certain value etc. These need to be checked. The function also will have various outputs. This is, of course, the result, and how the result should be structured, the method also can throw errors.

Write test cases

Essentially if the specification of the function is well defined it is very easy to write the test cases. You simply follow the specification write tests to get the expected correct results and willfully pass wrong arguments into the function. The rest of the lecture covers how to throw Exceptions. Which to use when.

HOMEWORK

Again another batch of “Java Tutor” exercises. They were as exciting as the last batch… However this time they also provided a “warm-up” problem set. The warm-up is just to implement the mathematical “quadratic roots formula”. The straightforward implementation of the formula will not pass all the Unit Tests. You need to take a deeper look at Java to actually figure out why the last Unit Test fails, and how you can change your code to make your code pass the test.

Notes on MITx: 6.005.1x Software Construction in Java (Week 1)

MITx has released a course titled “Software Construction in Java”. The course is aimed at more experienced Developers and is going to teach a couple of general principles of Software Development.

The course has the goal that you develop good code, which is defined as:

  • Safe from bugs: Correct behavior of the code, now and in the future
  • Easy to understand: Code should be easily understandable by other developers
  • Ready for change: Architectural patterns that allow you to modify the code without major rewrites.

Over the next couple of weeks, I will complete this course and will publish my notes and thoughts on the material. You can also take the course at https://www.edx.org/course/software-construction-java-mitx-6-005-1x

Why am I taking this course?

I have worked with Java in the past. I do not prefer using the language. However in the Python course from MIT was fantastic and thought very interesting concepts that apply to all languages. My hope is that this course will teach broader concepts and the language they are using just happens to be Java.

Lecture 1: Overview + Static Typing

The first lecture i skipped most of the videos, they seemed more like an introduction to Javas static typing, which I was already familiar with.

Lecture 2: Code Review

The second lecture takes a look at good Coding Practices.

Code Review

Lecture notes: The purpose of a code review has two main goals:

  • Improve the code
  • Improve the programmer

Personal notes: In reality on many programming projects the “Code Review”- Phase is cut due to budget constraints, lack of time and personal feelings. Remember when you do a code review you may hurt the feeling of another programmer, who thinks he is infallible. This usually causes that more and more bad code is written. Making the project not maintainable and unreliable. If it is possible for your project to do Code Reviews, you defiantly should do them, and have a very specific action plan that the other developer can learn from his mistakes.

Style Standards

Lecture notes: You can find good style guides at https://github.com/google/styleguide

Personal notes: Every programmer has his personal style how he likes to format and read his code. All university classes (including this one) do not provide a style guide. With the consequence that also no style guide is enforced. In larger projects this would not be possible. The version control systems suddenly cause problems, create merge conflicts etc. Styleguides should never be manually enforced. That would be tedious and create a lot of unnecessary work. The guide should be enforced by your build process. This prevents programmers from using their own style guide, avoids merge issues, is easier to manage, and it is psychologically better for the programmer that the machine rejects code rather than another programmer. The best practice would be that every code commit gets checked prior to be allowed into the repository. This ensures that every developer is playing by the same rules. (To find more information on this subject google for “git hooks” and “java checkstyle”)

Code Smells

  • Don’t Repeat Yourself (DRY)
  • Comments where needed
  • Fail fast
  • Avoid magic numbers
  • One purpose for each variable
  • Use good names
  • No global variables
  • Return results, don’t print them
  • Use whitespace for readability

Personal notes: While the lecture presents various strategies to prevent the most common beginner mistakes. These are just a select few of all the various types of code smells. I prefer to use the IDE IntelliJ, it has a feature called “Code Inspector”. It will scan your code and suggest fixes for a lot of types of code smells. Good code should never have obvious code smells.

Homework

For the “Java Tutor” Homework assignments you must use an Eclipse Plugin.  So sadly you have to use Eclipse with a custom built plugin and as usual I have had a lot of fun with randomly crashing Eclipse, the plugin giving me over and over again the same questions. The “Java Tutor” is overall quite weak. The questions are more like “fill in the blanks” and only accepts a single correct answer. Usually the titles of the links to the related materials give away the correct answer. However if you enter the wrong value, you can simply click “Show Answer”, copy the solution and progress without penalty.

Java: Multiple Functions and one ErrorHandler

Let’s say you have function fooA() and function fooB() both functions are very similar and throw similar errors.

 public static void fooA(){
         try{
             throw new FileNotFoundException();
         }
         catch (Exception e){
             exceptionHandler(e);
         }
     }

     public static void fooB(){
         try{
             throw new FileNotFoundException();
         }
         catch (Exception e){
             exceptionHandler(e);
         }
     }

If you have the possibility to avoid duplicating code you could write a single Error handler and pass the Error to the Error handling function. However, you still want to be able to distinguish between different types of Exception and for logging purposes, you should mention which function actually caused Exception. The easiest way to figure the Method name is to use e.getStackTrace()[0].getMethodName(); Alternatively, you can pass the method name to the Errorhandlerfunction. To do that you can figure out the method name via:

 String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

To determine the various Exceptions there are two possibilities:

Method 1: Use instanceof

The downside to this method is that it is not as readable and identifiable as ErrorHandling function. (However, this depends on personal preferences)

     public static void exceptionHandler(Exception e){
         if (e instanceof FileNotFoundException){
             System.out.println(e + " " + e.getStackTrace()[0].getMethodName());
         } else if (e instanceof Exception) {
             System.out.println(e.getStackTrace()[0].getMethodName());
         }
     }

Method 2: re-throw the Error

Well, you are still throwing around with errors, but it is clearly identifiable as Error handler.

  public static void exceptionHandler(Exception e){
         try {
             throw e;
         }
         catch (FileNotFoundException e){
             System.out.println(e + " " + e.getStackTrace()[0].getMethodName());
         }
         catch(Exception e) {
             System.out.println(e.getStackTrace()[0].getMethodName());
         }
     }

The cost of using Eclipse vs. IntelliJ

When it comes to Developing code, every developer has his/her own preferences. Some use Text editors and some use IDEs (Integrated Development Environments). An IDE combines several tools into one suite that allows more coding functionality than a single small text editor. Most Java Developers are using Eclipse, a free open source environment. This is basically because of the exposure effect during their time at the university. At the university, you get introduced to Eclipse, because it’s “free” and can support a lot of languages and can easily be extended with plugins. The same argument can be made for companies, the developers are already trained using the IDE and its “free”. IntelliJ Idea comes in two flavors, a community edition (free) and the ultimate edition (200$ – June 2014). When comparing these two IDEs at first glance it looks like both editors have almost identical features, however it is harder to extend IntelliJ with Plugins, fewer developers are using it, the community edition has core Java Development features, but most of the Enterprise features and languages are only supported in the ultimate edition which costs money. So yeah what’s the point of this article, the winner is Eclipse, a free open source software trumps evil company trying to make money. But wait, “almost identical” is not the same as “identical” features. Let’s take a closer look:

The feature Showdown

Saving Files

Yeah, well both Eclipse and IntelliJ can save files – what a surprise.   ** Eclipse:** Each tab signalizes with a “*” that you modified the file. Press Ctrl-S and your file is saved. If Eclipse crashes you lose all your changes.   IntelliJ: Do nothing. IntelliJ automatically saves every change you do not lose any of your work. On top of that, it stores a local history allowing you to undo changes even if you are not using a Version Control System.   Another benefit of autosave is when working with HTML/CSS you do not have to double-check if you correctly saved all files before viewing them in a browser.

Framework detection

Let’s say a new developer joins your team and he needs to get started. Now the environment must be set up for the new developer.   Eclipse: Does not have this feature for each developer you must repeat the same initial steps to get the framework running. Download the framework, place them in the project, and modify the project settings to include them as external libraries. Then double-check that everything is working correctly (due to human error you probably forgot something)   IntelliJ: “It looks like you are using the spring framework, should I set it up for you?” Automatically identifies and resolves dependencies. Then double-check if everything is working correctly.

File detection

You open a file in a project that uses the .py ending.   Eclipse: Opens the text editor.   IntelliJ:  (Ultimate Edition) opens the text editor + “It looks like a python file, we got a plugin for that, should I install it and restart to correctly display the file?”

Version Control Systems

Every project should use some sort of VCS system.   Eclipse: Well we got plugins go find the right one. Update: Eclipse 3.4 now has Egit a Java open source programmed git client integrated.   IntelliJ: The 5 most common VCS systems are seamlessly integrated into our system. In addition, the user interface is designed to have easy access to the most common VCS controls.

Copy and Paste Code-Blocks

A good practice is to rearrange your code in a standardized fashion. Could you collapse a code block and move that around?   Eclipse: when attempting to copy a collapsed code block it un-collapses it and you must redo the selection.   IntelliJ: copies the entire code in the code block. Note: This feature should be used for HTML stuff, copy and paste coding is a very bad practice.

Auto-completion

Eclipse: you must press Ctrl-Space to see suggestions that start with the letters you previously have entered.   IntelliJ: Uses context-aware auto-completion = it’s smart and at the same time no more pressing Ctrl-Space. If you want to set a String variable to the output of a function, it will suggest functions that return strings. It doesn’t matter if the function starts with the keystrokes you have entered it checks if the function contains your keystrokes.

Coding Guidelines

Style guides are used to coordinate, standardize and promote good coding practices. https://code.google.com/p/google-styleguide/   Eclipse: Syntactically correct Java is good enough.   IntelliJ: Underlines code that is not following the guidelines. With pressing Alt-Enter IntelliJ automatically corrects the code to follow the guidelines.

Better Code

Java is constantly evolving and improving. Take for example the shorter for each loop syntax.   Eclipse: Java is syntactically correct. No indication that the loop may result in an “array out of bounds exception”.   IntelliJ: You could rewrite the code with the shorter for each syntax and avoid the array out of bounds exception. Press Alt-Enter and the code gets rewritten with the new syntax. This does not only apply to Java but to practically every language IntelliJ supports, like CSS shorthand syntax, alt-enter and the code are shorter etc.   IntelliJ also has a “rearrange code” functionality, which automatically rearranges variables and functions based on the coding guidelines.

Better Documentation

Nobody likes to write documentation, even less double-checks when changing the function if the documentation is still correct.   Eclipse: missing feature   IntelliJ: With just typing /* before the function it automatically creates a Javadoc comment string with all parameters in the correct format. The code validator checks if all doc strings are completed, fixes spelling mistakes and notifies you when modifying the function that the doc-string has errors.

Other stuff:

IntelliJ indexes everything and is really fast while searching for text compared to Eclipse   The Company behind IntelliJ wants to sell a product, thus they have the interest to keep their customers happy and fix bugs and provide new features that the community requests. While Eclipse is open source and says: you want a feature, well then build it its open source dude.

Cost analysis

Now you may say well those are nice features, but altogether it is not worth it. There is no benefit besides minor usability tweaks. You may save a couple of seconds here and there but overall – meh.   Initially, it may seem that way, however, If you are working with a team, not all team members have learned to code following the same standards you are following and practically never follow coding guidelines. By having the program subtly reminding team members to improve their code quality – in the long run, the code will become more easy to read and more easy to maintain. That is a huge benefit for any software development project.   But you are not working with a team, even then you can befit of clearer code, thus fewer bugs, thus more time for other stuff. Overall you will be quicker more focused on your work, have less jumping around in your code, it’s easier to get a new developer up to speed, and for me, that’s a clear efficiency and quality win.

Cost of switching from Eclipse

For the transition phase, you still can use both editors, IntelliJ can import and export Eclipse projects without any major conflicts.   The colors can be customized to be the same color scheme as Eclipse (http://www.ideacolorthemes.org/home/)   But you really don’t want to switch because you memorized all your keyboard shortcuts. Well, IDEA has got you covered there as well IntelliJ has a preset to use map the IntelliJ functions to the eclipse keyboard mapping.

But it costs Money

Well can I ask you a question, are you a professional developer? If you are by definition you are getting paid for your work. So some customer values your programming skills, it’s the same thing when you buy software from somebody else and I bet you have bought some computer games.   It costs you initially 200usd = 1usd/day, then 100usd/year= 0.5usd/day. In addition, the costs are tax deductible (depending on your country, I am no tax expert).   Look at it as a tool that will make your life easier and more relaxed. A professional tool for a professional developer.

Result

The program has many more features and I am still discovering new features every day.  While Eclipse is designed to be a platform for plugins, IntelliJ is designed as a professional development tool.   Eclipse is initially free, however, the 200usd price tag negligible compared to the weeks of work that can be avoided by having better code standards and higher code quality and documentation. IntelliJ proactively supports and encourages developers to write more stable robust and maintainable code while at the same time increasing development speed.   I only can recommend that you try out IntelliJ and decide for yourself which environment better suits your need. If you are a student or just have started learning Programming check out the community edition.  If you are working in an enterprise environment try the ultimate edition.   http://www.jetbrains.com/idea/download/       Some more Resources:   http://java.dzone.com/articles/why-idea-better-eclipse

Java GUI: Using AbstractTableModel

Using the AbstractTableModel the easiest way to store the table data is to use a Vector of Vectors. You have to implement additional functions to insert new data.

Here is the example:

import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class AbstractTableDemo extends JPanel {

 public AbstractTableDemo() {
  super(new GridLayout(1, 0));

  final JTable table = new JTable(new MyTableModel());
  table.setPreferredScrollableViewportSize(new Dimension(500, 70));
  table.setFillsViewportHeight(true);

  Object[] values = {
   "String",
   10,
   20.0,
   30.2,
   new Boolean(false)
  };
  MyTableModel a = (MyTableModel) table.getModel();
  a.insertData(values);

  //Create the scroll pane and add the table to it.
  JScrollPane scrollPane = new JScrollPane(table);

  //Add the scroll pane to this panel.
  add(scrollPane);
 }

 class MyTableModel extends AbstractTableModel {
  private String[] columnNames = {
   "Title A",
   "Title B",
   "Title C",
   "Title D",
   "Title E"
  };

  private Vector data = new Vector();

  public final Object[] longValues = {
   "",
   new Integer(20),
   new Float(20),
   new Float(20),
   Boolean.TRUE
  };

  @Override
  public int getColumnCount() {
   return columnNames.length;
   private String[] columnNames = {
    "Title A",
    "Title B",
    "Title C",
    "Title D",
    "Title E"
   };

   private Vector data = new Vector();

   public final Object[] longValues = {
    "",
    new Integer(20),
    new Float(20),
    new Float(20),
    Boolean.TRUE
   };

   @Override
   public int getColumnCount() {
    return columnNames.length;
   }

   @Override
   public int getRowCount() {
    return data.size();
   }

   @Override
   public Object getValueAt(int row, int col) {
    return ((Vector) data.get(row)).get(col);
   }

   public String getColumnName(int col) {
    return columnNames[col];
   }
   public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
   }

   public void setValueAt(Object value, int row, int col) {
    ((Vector) data.get(row)).setElementAt(value, col);
    fireTableCellUpdated(row, col);
   }

   public boolean isCellEditable(int row, int col) {
    if (4 == col) {
     return true;
    } else {
     return false;
    }
   }

   public void insertData(Object[] values) {
    data.add(new Vector());
    for (int i = 0; i & lt; values.length; i++) {
     ((Vector) data.get(data.size() - 1)).add(values[i]);
    }
    fireTableDataChanged();
   }

   public void removeRow(int row) {
    data.removeElementAt(row);
    fireTableDataChanged();
   }
  }

  private static void createAndShowGUI() {
   JFrame frame = new JFrame("Abstract Table Demo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   AbstractTableDemo newContentPane = new AbstractTableDemo();
   frame.setContentPane(newContentPane);

   //Display the window.
   frame.pack();
   frame.setVisible(true);
  }

  public static void main(String[] args) {
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
     createAndShowGUI();
    }
   });
  }
 }