Yakov Fain's Blog

My notes about everything in IT

JavaScript for Java/C#/C++ Developers

leave a comment »

This year I’m planning to run a one day workshop at a couple of software development conferences and privately for IT shops. The goal is to introduce JavaScript and related technologies to developers that are accustomed to developing in classical object-oriented languages like Java, C++ or C#. Below is the outline of this workshop.

Part 1. JavaScript Building blocks

* Functions, Objects, Prototypal Inheritance,Closures
* Using Chrome Developer Tools
* JavaScript in the Web Browser, DOM, CSS.
* New JavaScript: an overview of selected ECMAScript 6 features.

Part 2. Designing Single-Page Web Applications

* Web app prototyping. Designing a Product page of an online auction using Pure JavaScript and CSS.
* Responsive Web Design. CSS Media Queries. Redesigning the Product page for smart phones and tablets by adding CSS Media Queries. Our Product page will look like this.
* Single-Page Applications. AJAX.
* The Bootstrap framework. Responsive GUI components. Fluid grids. Yet another redesign of the Product page by using responsive Bootstrap components.

Part 3. Productive JavaScript development with Google Dart

* Getting familiar with the Google Dart language. Classes, top-level functions.
* Dart Tooling. Dartium VM. Dart Editor IDE. Dart to JavaScript Compiler. Package manager pub.
* Re-creating the Product page in Dart + Bootstrap. JavaScript generation and deployment.

Written by Yakov Fain

January 22, 2015 at 2:27 pm

Posted in java

Why You Should Start Developing With Google Dart

with 14 comments

In the summer of 2013 I wrote a blog “How Serious is Google About Dart“. It’s January of 2015, and I’d like to give you an update from the trenches. Our team has developed and deployed in prod a beta version of the application that helps consumers with finding and rating insurance agents and getting quotes online. The front end of EasyInsure is written in Dart language.

Before introducing the Dart ecosystem, I’d like to give you a little background about our prior experience in developing Web applications (I work for Farata Systems).

On the server side we always use Java and have no plans to switch to any other technology. After spending many years developing the front end with Adobe Flex framework and ActionScript programming language we got spoiled by this super-productive environment. After the mankind led by Apple killed Flash Player, we started to look for an alternative.

Back in 2005 we’ve abandoned JavaScript, but decided to give it another chance. Things were a little better this time. JavaScript has better IDEs and browser-based tools for developers. The number of JavaScript frameworks and libraries went down from two hundred to a couple of dozens, which is a good thing.

Still, the productivity of our developers dropped substantially in JavaScript comparing to what we’ve seen with Flex. I can’t give you exact numbers, but it looks like developing in Flex is at least three times faster than with any JavaScript framework we tried (ExtJS,AngularJS, and lots of small libraries). When I say JavaScript, I mean its version based on the ECMAScript 5 specification.

In 2013 we got familiar with the Google Dart language. The syntax of the language was pretty appealing and easy to understand. It felt like Java, but a little more modern. Dart is optionally-typed language. You can run the compiled Dart code in DartVM, but no browser except Dartium support it, and it’ll remain this way. Generating JavaScript from the Dart code is a realistic way of delivering Dart applications for any browser today.

But any language without the proper tooling is doomed, and this is what makes Dart stand out. Here’s the list of tools available for Dart Developers:

1. The IDEs: Dart Editor from Google and WebStorm from JetBrains. We use Dart Editor because it’s smarter than WebStorm today.
2. dart2js is a Dart-to-JavaScript compiler and a tree-shaker, which removes the unused code from the third-party libraries used in the application.
3. pub is a dependency management, development server and build tool.
4. gulp is a task manager. It’s an analog of Grunt or Gradle. We use gulp to prepare optimized ready-to-deploy application from the code produced by the pub build. In particular, we do the gzip compression there.
5. Dartium is a Web Browser for developers. Google Chrome is based on the open source project called Chromium, and Dartium is Chromium with built-in DartVM. We use it for launching and debugging applications.
6. Dump-Info Visualizer – allows to inspect the generated JavaScript. It gives a very convenient breakdown by the application’s JavaScript code so we can analyze file sizes and identify the scripts to be optimized.
7. Observatory is Dart profiler (we haven’t used it yet).
8. AngularDart framework. It’s a port of a popular JavaScript framework AngularJS.

The above list is pretty impressive, isn’t it? As Google Dart evangelists say, “Batteries included”.

Developing JavaScript applications in Dart is definitely more productive. I do recommend you to start learning Dart and develop the front end of your Web applications in this developer-friendly environment. Having said that, I’d like to warn you that there are no jobs on dice.com that require programmers with Dart skills. Oops… Moreover, three years from now your Dart skills may be in even lesser demand in the enterprise world. Oops…

After these two oopses half of the readers may lose interest to Dart, because it doesn’t meet their career objectives. For those of you who continue reading I’ll explain why IMHO you still should learn and use Dart today. Because the final release of ECMAScript 6 (ES6) is around the corner. Because this spec already gave birth to JavaScript 6 (it’s a boy)!

By the way, do you know why there is no enterprise jobs that require Dart skills? Because enterprise architects will fight hard against any language that runs in a browser unless it’s called JavaScript. Back in 2007 Adobe sales force did a great job by pushing Flex framework into enterprises. Enterprise architects were fighting hard against Flex then, and they will do the same with Dart. But Google is not Adobe. They won’t fight for Dart in enterprises.

But promoting Dart in your organization can be easy. Just explain your enterprise architects that programming in Dart is just a smart way of preparing the enterprise to embrace the bright JavaScript 6 future with classes,modules, promise, fast image rendering, et al. The code that you’ll be writing in Dart during the next 12-18 months will need to be converted into EcmaScript 6 as soon as several major Web browsers will start supporting it.

The syntax of Dart and ES6 are literally the same. Google invested time and resources in creation of IDE for Dart, and now they’re working on the IDE for ES6. Even manual refactoring of the code from Dart to ES6 shouldn’t be a major project, but I’m sure this process will be automated soon.

As a matter of fact, some browsers already started supporting ES6. See for yourself:


I’d like to draw your attention to the greenest column on the right side. Yes, it’s the successor of the today’s funniest browser known as IE! Microsoft calls it Spartan, and promises that Spartan will be a lightweight browser that feels like Chrome or Firefox. You just can’t go wrong with such a name.

Spartan already supports ES6. Courageous early adopters can start developing code in ES6 now, than compile the code down to ES5 with Traceur compiler and deploy it in any today’s browser. But if you want to work in a tools-rich environment just develop your single-page applications in Dart and AngularDart. Give the ES6 some time to mature. The work on ES7 is being done too, and it looks very interesting and promising.

I’ve created a New York City Dart Meetup with a hope to get some Manhattan-based firm to host our meetings in the future. Meanwhile we’ll run our meetings online so you’re welcome to join no matter where you are located. Go Dart if you need to deliver today!

Written by Yakov Fain

January 8, 2015 at 1:52 pm

Posted in dart, javascript, Web

Pushing data to multiple WebSocket clients from a Java server

with 4 comments

Finished writing the WebSocket chapter for the second edition of my Java 24 Hour Trainer. In this blog I’ll show you one of the code samples from lesson 28.

Pretty often you need to write a program that publishes the same message to all connected clients. For example, multiple clients of the online auctions have to be notified when a new bid is placed on the product. Another example is when a new stock price quote need to be pushed from the server to all connected clients. With websockets it’s a pretty easy task.

I’ll show you a basic example when a WebSocket endpoint pushes the server’s time to all connected clients. If you can publish the server’s time to all connected clients, you can publish any application-specific data.

The following endpoint WebSocketClock schedules the task that gets and formats the server’s time every second and publishes the time to all connected clients. I schedule this timer once when the first client connects to our endpoint. The method sendTimeToAll() finds all connected clients by invoking getOpenSessions() on the Session object. Then on each session it calls getBasicRemote().sendText().

public class WebSocketClock { 

  static ScheduledExecutorService timer = 

  private static Set<Session> allSessions; 

  DateTimeFormatter timeFormatter =  
  public void showTime(Session session){
      allSessions = session.getOpenSessions();

      // start the scheduler on the very first connection
      // to call sendTimeToAll every second   
      if (allSessions.size()==1){   
             () -> sendTimeToAll(session),0,1,TimeUnit.SECONDS);    

   private void sendTimeToAll(Session session){       
     allSessions = session.getOpenSessions();
     for (Session sess: allSessions){          
          sess.getBasicRemote().sendText("Local time: " + 
          } catch (IOException ioe) {        

The Web client is pretty simple. On the page load the JavaScript code connects to the WebSocket endpoint on the server. The callback onMessage() is invoked when the message (current time) arrives. In this callback I update the content of the span HTML element with the current time. Since my Java code will send the message every second, the span content updates with this frequency. No page refreshes, no heavy HTTP headers, no AJAX long polling hacks either.

<!DOCTYPE html>
<meta charset="UTF-8">
  <span id="messageGoesHere"></span>
  <script type="text/javascript">
    var ws = new WebSocket("ws://localhost:8080/Lesson28/clock"); 
    ws.onmessage = function(event) {
      var mySpan = document.getElementById("messageGoesHere");
    ws.onerror = function(event){
        console.log("Error ", event)

The next screenshot shows how Eclipse internal browser, Chrome, and Firefox display the current time published by my WebSocket endpoint.


Three Web clients get current time published by a WebSocket endpoint every second.

Iterating through all open sessions works fine if the number of connected clients is small. But if you have hundreds of clients, consider grouping the Session objects into separate collections in @OnOpen message handler, and sending messages to each group in parallel from multiple threads. Important: by default, a Java EE server creates a new instance of the server endpoint class for each client’s connection, so if you’ll be creating your own session collections they must be static:

private static Set<Session> sessionsChunk1 = Collections.synchronizedSet(new HashSet<>());
private static Set<Session> sessionsChunk2 = Collections.synchronizedSet(new HashSet<>());

Written by Yakov Fain

December 29, 2014 at 6:45 am

Posted in html5, java

Tic-Tac-Toe in JavaFX

with 15 comments

Finished writing the JavaFX chapters for the second edition of my Java 24 Hour Trainer. It included a sample code of the Tic-Tac-Toe game. The front end is done in FXML and the application logic is written in Java.


Using FXML allows to substantially minimize the amount of Java code. This application has 200 lines of code, namely:

Tic-Tac-Toe.fxml: 45 lines
Main.java: 27 lines
TicTacToeContoller.java: 118 lines
application.css: 12 lines.

The FXML and CSS files can be created and modified by people who do not know Java at all (i.e. graphic designers). I haven’t implemented a couple of menus, which would add a couple of dozens lines to the code base. Pretty concise, isn’t it? The source code of the Tic-Tac-Toe project is available among other code samples at https://github.com/yfain/java24hourtrainer2ndedition. I’ve developed this in Eclipse IDE with the E(fx)clipse plugin that generated an initial project for me. At the time of this writing NetBeans 8 IDE has the best support of JavaFX followed by IntelliJ IDEA 14, and then goes Eclipse with E(fx)clipse plugin.

Written by Yakov Fain

November 20, 2014 at 6:22 am

Posted in java

Tagged with ,

Have you shortened your talk yet?

with one comment

Attention span is getting shorter and shorter. At least mine. I can’t do the same thing for 50 minutes straight, can you? Books became thinner. In the past getting a 1500-page book on programming for $40 would be considered a good deal. Now people don’t want to buy books that have more than 500 pages. In my recent book project the publisher decided to not include a 60-page chapter in the printed version, but offered it as a free online bonus chapter. The chapter content was good, but marketers said that thinner books sell better.

IT conferences should follow the same trend. 50-minute presentations are so last century! Some conferences include ignite talks. They last 5-10 minutes, and ideally, the slides should be flipped automatically to force presenters stay focused. This is called Pecha Kucha.

I can share a secret with you: I can deliver a 50-min presentation in 25 min. Or in 15. Or in 5. Just tell me how much time I have, and I’ll remove the irrelevant content. It’s like extracting juice concentrate.

Shorter presentations would require better concentration not only from the speakers, but from the audience as well. There is no time for checking emails, tweets, or reading the news. As a matter of fact, the conference organizers wouldn’t need to pay outrageous amounts of money for providing this flaky Wi-Fi connections for the audience. No time for Internet browsing.

A typical IT conference runs for 3-4 days averaging 7 presentation slots per track daily. What if each presentation would run for half the time – 25 minutes? A rare conference would run for more than two days. This translates into cost savings for both conference organizers and those who pays for a trip to the conference. For those who who are not in the know, I have another secret to share. Remember that airline-quality lunch that you got for free? The conference organizers paid anywhere from $50 to a $100 for each plate.

Can software developers absorb 14 presentations a day? Yes, we can. But realistically, none of the conferences can offer 14 interesting presentation a day. Except one. TED. BTW, I don’t remember ever watching a TED presentation that was longer than 25 minutes, and they were all great!

Can IT conferences follow the leader? Yes they can. Last month I was participating in the HTML5Dev/IOTA conference in San Francisco. Take a look at the schedule. It was based on 20-min slots. But if a speaker wanted to talk for 50, he would get 2 slots + 10 minute break. It worked like charm.

Pretty often attendees find themselves in a wrong auditorium after the first 5 minutes into the talk. Some of them are shy to simply walk out. 50 minutes of their time wasted. If the presentations were shorter, they would have wasted only 20 minutes!

Anyway, this blog is getting too long too, but as someone said, “Sorry, I din’t have time to write you a shorter letter”.

Written by Yakov Fain

November 13, 2014 at 1:43 pm

Posted in java

IT book publishers may extinct soon

with 3 comments

Not sure how IT book publishers can survive these days. People are intoxicated with free content. During American Civil War soldiers were bringing liquor to the camps by hiding it in their boots (a.k.a. boot-legging). But this is the ancient history of America. With soft media, there is no need to hide anything in the boots. You can find almost any content online for free. I’ll give you one of the examples that directly relates to me.

After spending lots and lots of hours writing the book “Enterprise Web Development”, preparing code samples and going through several rounds of editing, the book is finally in print. Lots of people besides the authors were involved in the process. During the entire process the drafts of the all chapters were available online for free. Thank you O’Reilly Media! The idea was to build a community while the book is being worked on.

Now the book is printed. Booksellers get it from the publisher for about 50% of the list price. The publisher paid the authors an advance, which is ours to keep even if not a single copy of the book is sold. The publisher takes a risk. If the book sells well, the author(s) will get a dollar or two in royalties for each sold copy. We’ll split the royalties for this book (if any) between four coauthors, so it’s clearly a not-for-profit project for us. Now check this out:


Two thousands of free downloads just at this pirate site. It’s great for the authors that the book is popular. All authors are working programmers, and our income doesn’t depend on book sales. But this book is a good PR for us and our company (all work for Farata Systems). Read the book, and hire us for your next consulting project! Book writing worked for us really well so far. Our company exists since 2006 and we never had even a single salesman. PR works. It sounds like a paradox, but the more bootlegged copies will be distributed, the better it is for us!

But what about the publishers? How they are supposed to make a living? I simply don’t know. It’s sad to see how the IT sections in the bookstores are shrinking, but this trend will continue.

Written by Yakov Fain

November 11, 2014 at 10:16 pm

Posted in java

Programming to Interfaces in Java

leave a comment »

Seasoned Java programmers are programming to interfaces. What does it means?

Let’s consider a simple example. Let’s say I’ve declared a variable customers of type ArrayList:

ArrayList<Customer> customers = new ArrayList<>(3);

While this code is correct,  there a better way of declaring the variable customers:

List<Customer> customers = new ArrayList(3);

You can read the first example as follows: “I want to declare a variable customers that will have all access to all API offered by the class ArrayList“. The second version means the following: “I want to declare a variable customers that has a behavior declared in the List interface”. The first example declares a variable of a specific implementation of the List interface – ArrayList. Now rake a look at this code example:

ArrayList<Customer> customers = new ArrayList<>(3);

// The code to populate customers with instances of 
// Customer is omitted for brevity

int totalElem = customers.size();

// Iterate through the list customers and do something with each
// element of this collection

for (int i=0; i<totalElem;i++){
    Customer currentCustomer= customers.get(i);

ArrayList implements several interfaces besides List, which means that it has more methods that the List defines.  But if you read the documentation on the List interface, you’ll see that among others it includes the methods as add(), get(), and size() , which are the only ones used with our collection customers. If this is all we need, declaring a variable customers of type List gives us more flexibility. If later we decide to switch to a different implementation of the List (e.g. LinkedList instead of ArrayList ) we won’t need to change the type of the variable customers.

You may say that changing a variable declaration from ArrayList to LinkedList it’s not a big deal – it’s still the same line of code. But it may be a bigger deal if, say you program needs to pass the object referred by customers to another object’s method that also was declared with the argument of type ArrayList:

processCustomers (ArrayList<Customer> customers){


Now we need to change both the variable and the method argument declarations . In large projects such a refactoring may become a time consuming process.

If you just need a behavior defined in a particular interface (e.g. List), declare the variable of this interface type rather than of a concrete implementation (e.g. ArrayList) of this interface.

P.S. Here’s the Java 8 way of writing the above loop, which is not relevant for the blog subject:

customers.forEach( customer -> System.out.println(customer));

Written by Yakov Fain

October 26, 2014 at 2:34 am

Posted in java

Tagged with


Get every new post delivered to your Inbox.

Join 155 other followers