How to Use Advanced Search Expressions with Mojarra, MyFaces or OmniFaces

I consider the advanced search expressions of PrimeFaces and BootsFaces tremendously useful. In particular, @next and @previous make it a lot easier to move input fields around on the screen or from one screen to another during the prototype phase of your project. The only problem with the search expressions is that they only work with PrimeFaces and BootsFaces components. If you also use the base components like <h:inputText />, you back to using ids and the four search expressions defined by the JSF standard (@form, @this, @all and @none).

JSF 2.3 may change that. It’s not settled yet, but there an ongoing discussion to include a similar search expression framework in JSF 2.3.

But what about now?

That’s a bright look-out. Problem is, most of us live don’t live in the future. Quite the contrary, from a technical point of view, most of us developer live in the past. I know many projects currently developed with JavaEE 6, a technology presented seven years ago. In other words: even if Oracle is going to accept our proposal in JSF 2.3, that doesn’t help many developers before 2020. So the challenge is to find a way to add the search expressions to JSF 2.0, 2.1, and 2.2.

How to do it

Cutting a long story short: I’ve found such a solution. It’s not exactly elegant, but it does the trick. The nice thing about my solution is that you don’t need to add the BootsFaces library to your project just to use the search expressions. You only need a single package of BootsFaces. Most likely I’m going to publish this package on Maven Central after running some more tests.

Actually, it’s fairly simple to use the search expressions in non-BootsFaces components. Every attribute of a JSF component supports EL expressions. This includes the attributes for, render and execute. So I’ve defined a JSF bean allowing you to resolve the advanced search expressions:

<h:message for=
 "#{searchExpressionResolverBean.resolve(component, '@previous')}" />

Of course, that’s a far cry from what we really want:

<h:message for="@previous" />

Luckily, there’s a second option we can use to simplify things. JSF allows us to register a “facelets decorator”. This class is called when the XHTML file is loaded and parsed. The facelet decorator can modify each facelet and replace it with another facelets. That’s how the HTML5 friendly markup of JSF 2.2 has been implemented. The JSF 2.2 recognizes an HTML input tag and replaces it with a JSF h:inputText if there’s an JSF attribute. We can use the same trick to replace the string "@previous" by "#{searchExpressionResolverBean.resolve(component, '@previous')}"". In other words, our decorator translates the search expressions to something core JSF can understand at load time.

How to activate the search expressions

Unless you’re already using BootsFaces, copy the folder to your project. This folders contains the entire search expression resolver library, and it also contains the decorator in a subfolder.

If you want to benefit from the simplified syntax of the decorator, you have to activate it by adding a few lines to your project’s web.xml. If you don’t use BootsFaces, that’s:


If you use BootsFaces, chances are you also want to benefit from the full power of the relaxed HTML5-like coding style of BootsFaces. If so, you have to register a different, more powerful decorator:


Limits of the decorator

I encountered a surprising limitation of the decorator when I tried to use it with f:ajax. Both the render and the execute attribute are translated by the decorator, but they are ignored – at least by Mojarra (I didn’t try MyFaces yet). That’s fairly annoying because it forces you to use my first, verbose proposal. You can abbreviate the long name of the JSF bean SearchExpressionResolverBean by deriving a bean with a shorter name, but there’s no way to reach the simple syntax we really want.

Still, being able to use advanced search expressions with frameworks like Mojarra, MyFaces, RichFaces, or ButterFaces that haven’t been designed to be extended that way is nice.

Benefits for users of BootsFaces and PrimeFaces

Every once in a while, even users of such huge libraries like PrimeFaces (157 components) and BootsFaces (68 components) need a component that’s not part of the library. A popular way to build components is to build them from scratch using the base libraries. Another popular way is to add a library like OmniFaces, that’s not aware of the search expressions, either. But it does contain components like <o:commandScript /> that may benefit from the search expression.

By the way, if you prefer PrimeFaces over BootsFaces, you can also use their search expression framework. I didn’t prepare code to use it, but it’s fairly simple. The source code is at The key class is the SearchExpressionFacade. There’s no facelets decorator, but I’m sure you’ll be able to migrate the BootsFaces facelets decorator to PrimeFaces within a few hours.

Benefits for the rest of the JSF world

Well, that’s fairly obvious: you couldn’t use the advanced search expression before. Now you can. More likely than not, you don’t see the use case use. But that shouldn’t stop you. Just give @next, @previous, @parent, @after, and @styleClass(.) a try. Before you know, you’ll be addicted. Using fixed ids may be the most efficient way with respect to CPU usage, but at the same time, it’s very inflexible and limited if your JSF views are changed frequently. The advanced search expressions of PrimeFaces and BootsFaces make moving fields from one panel to another or from one view to another a breeze.

Wrapping it up

JSF is very flexible. So it’s possible to add search expressions to JSF using a couple of tricks. However, the f:ajax facet of JSF seems to ignore the changes of the facelet decorators, so the result isn’t as nice as it’s intended to be. But still, it’s nice to able to use the advanced search expressions in JSF 2.2 or below.

What’s New in BootsFaces 0.9.0?

Fork me on GitHubAfter seven weeks of hard work, we’ve published BootsFaces 0.9.0. It’s a major improvement over BootsFaces 0.8.6. Unfortunately, a little error slipped through our QA gate: It seems we’ve involuntarily published a Java 8 version. If you are using Java 6 or 7, you’ll have to wait until 0.9.1 comes out in a few weeks, or you may use the developer snapshot on Maven Central. It was a small bug, easy enough to fix it within a day.

While BootsFaces 0.9.0 is more than a bug-fix version, it clearly concentrates on polishing BootsFaces, removing bugs and finishing things we had started in previous versions. That’s not a small achievement: Fork me on GitHub the number of commits on GitHub went from 856 (BootsFaces 0.8.6) to 1028. And that’s only the base library. The showcase has improved a lot, too. And we’ve managed to finish a component many developers desperately need: <b:dataTable />. What makes this component unique in the JSF world is that it is rendered on the client. That makes it feel a lot faster and much more responsive than traditional server-side data tables. We’ve already received a lot of bug reports and enhancement requests, even during the development phase. Thus I’m sure the data table will remain in our focus during the new few updates of BootsFaces.

A more liberal license

Probably the most important point of BootsFaces 0.9.0 is the license. Now, BootsFaces is available under an Apache V2 license being a lot more liberal than the old GPL V3 license. For example, you can use BootsFaces in commercial products without further ado.

Continue reading

Newsflash: OmniFaces 2.4 has been Released

OmniFaces 2.4 has been released. This time, the new version concentrates on bug fixing and polishing. There is only a handful of new features, the most notable being <o:url />, which bring the old <o:url /> of JSF 1.x back to the JSF 2.x world. There are also improvements to the FullAjaxExceptionHandler and better support for logging. As usual, the team has written an exhaustive blog post covering the changes, so I won’t repeat their description. Instead, I suggest you follow the links below.

JSF 2.3

Maybe more important is that the OmniFaces team brought a couple of features from OmniFaces to the upcoming JSF 2.3 standard. That’s exciting because it puts the commotion about Oracle’s presumed withdrawal from JavaEE into perspective. Even if the rumors we to come true and Oracle were to stop their efforts on JavaEE, it wouldn’t be the end of the Java world. If need be, there are other developers ready to contribute suggestions, improvements, code and documentation.

Dig deeper

Announcement written by BalusC
What´s new in OmniFaces 2.4?

Newsflash: Comma Separated Json

Recently I noticed how cumbersome Json becomes if it’s used to describe large quantities of simple data. Have a look at the definition of the Coffee Wheel created by (no pun intended!) Jason Davies. On the one hand, Json is a great and simple format to describe the wheel (see the source code). On the other hand, writing your own coffee wheel description is another story altogether. You have to count curly braces, square brackets, commas, and quotation marks meticulously. It almost drove me nuts.

This shows another problem of Json. It’s not well suited for stream processing. Json objects are JavaScript objects, so they have to be parsed completely before you can start working. That’s one of the few area XML has an edge of Json. Since 2004, XML stream processing is an official part of JavaSE.

So I became curious when I stumbled of the CSJ API of Kirit Sælensminde. I didn’t try it, so I can’t say anything about the quality of the implementation, but at first glance, it looks both well-thought and promising. In many cases, the Json stream object is just as simple as a traditional CSV file you can import by Excel, but it offers much more flexibility.

By the way, CSJ wouldn’t simplify the coffee wheel description. The coffee wheel is a recursive data structure, so it doesn’t benefit from stream processing.

Progressive Web Apps

The other day, we had a discussion in the office. Is HTML5 the solution to every problem, or are native apps the way to go?

For a long time, I was very reluctant to force our users to use the browser to do their work. At the time, we had a nice Java applet running in the browser, which seemed to be a nice compromise to me. We could offer a rich user interface, and every user who had access to the internet could install our application. But installing the applet soon turned out to be above the skill and will of the average user, causing a lot of hotline calls. Plus, developing simple HTML pages was cheaper. That tipped the scales. We kissed Swing goodbye and never looked back.
Continue reading

HTML Includes

Almost every programming language offers you an option to use the content of another file in the file at hand. Basically, it’s a very old idea. Sooner or later programs become large and larger, so developers started to split the files into smaller building blocks. First, they invented subroutines, later procedures, and functions. Later they invented higher-level building blocks like modules, classes, and packages. One of the early ideas was to include the content of another file. To a certain extent, that’s always been possible in HTML. You can include CSS files by writing <link rel="stylesheet" href="myFavoriteCSSFile.css">. Similarly, you can add JavaScript code stored in an external file by writing <script src="myFavoriteScript.js">.

Funny thing is there’s no way to include the content of an HTML file into another HTML file.

That’s very strange because it’s such a useful feature. Server-side languages like PHP fix the problem by providing server-side includes. Probably that’s why the HTML standardization team didn’t add HTML import prior to HTML5. Even so, a quick glance at is a bit disappointing. You can use the official W3C standard on Chrome, Opera and Android. A second closer look reveals that this particular HTML5 standard is still in the “draft” stadium at the time of writing (June 2016).

What may be in store for you

Let’s start with the current W3C draft which may or may not see the light of the world. To my surprise, it’s not a simple HTML include, but requires some JavaScript code. So, the recommended way to use HTML includes seems to add the include statement – which turns out to be a <link /> – in the header of your HTML page:

  <link rel="import" href="myFavoriteInclude.html">

The next step is to define a div in your HTML page which is going to contain the include file:

     <div class="put-include-here">
        This message is going to be replaced by the include file.

Finally, you put the content of the include file into that div:

    var link = document.querySelector('link[rel="import"]');
    var content = link.import;
    var el = content.querySelector('.put-include-here');

This is a bit cumbersome, but of course, it’s much more flexible than a simple HTML include. You can do anything with the file loaded by the import link. When I tried this feature, I was even able to load different files by changing the href of the <link /> tag from JavaScript. A write access to the href was enough to make the browser load the file.

Still, this version is a bit disappointing because I’d prefer a simple way to include HTML code. Fiddling with JavaScript is a nuisance. It’s nice to have the option, but it’s annoying you can’t do without. But then, modern HTML5 is flexible enough to write a simple polyfill providing the feature I’m looking for:

     <include-polyfill href="myFavoriteIncludeFile.html" />


AngularJS comes close to my ideal solution:

<body ng-app="someApp">
   <div ng-include="myFavoriteIncludeFile.html"></div>

There are only two drawbacks. First, you have to use AngularJS. That’s fine if you want to use it anyway, but it’s a no-go otherwise. Second, AngularJS cares about security. It goes without saying that security is a good thing, but in this case, it means many tags are ignored by <ng-include />. In particular, you can’t include JavaScript code. If you want to do such a thing, you have to write some additional code to make AngularJS forget about security.


I didn’t try this one, so I can say little about it, but it appeared on the front page of my search result, it looks nice, and it comes from a source I consider trustworthy, so chances are that w3IncludeHTML is a good alternative for you. Using it seems to be pretty straightforward:

<!DOCTYPE html>
    <script src=""></script>
    <div w3-include-html="myFavoriteIncludeFile.html"></div> 


I take it most of you use jQuery, so using jQuery to load the include file is little to no overhead. As usual, jQuery isn’t activated by an HTML directive like <w3-include-html />, but it’s activated by a single line of JavaScript code:


Wrapping it up

When I started this article, I wanted to rave about the simplicity of the new HTML5 standard. Along the way, I learned that the new HTML5 standard isn’t as simple as I expected it to be: it requires a little help from JavaScript. Adding insult to injury, it’s not exactly a standard. It’s supported by Google Chrome, which may be a very popular browser, but which isn’t the most popular browser in the enterprise world, at least not in every country. So a substantial fraction of readers needs an alternative. Luckily, there’s an abundance of alternatives. Searching for “HTML include” reveals no less than 650 million search results on Google. So I’ve picked three arbitrary solutions: AngularJS, jQuery or a W3Schools library for those who don’t want to use nor Angular nor jQuery.

Still, I wonder why such a simple feature hasn’t made it into the HTML standard yet. Probably that’s due to the “good enough” principle. Most web designer and web developers can use another solution, such as PHP server-side includes, so they don’t need HTML includes.

Newsflash: Material Design with Materialize.css

This morning I became aware of a nice CSS library: Materialize.css. In many respects, it reminds me of Bootstrap. Among other things, there’s a similar grid system, which is even slightly simpler and more logical than its Bootstrap counterpart. The class names are shorter, there are only three screen sizes, and my first impression it’s easier to learn “s, m, l” than “xs, sm, md, lg”.

Community support (speculative until confirmed by further research)

What caught my attention was the ambitious translation of the huge showcase. The German translation is pretty good, and my quick survey showed that the Spanish and French translations aren’t bad, either. Granted, the major part of the showcase is yet to be translated. But some time ago, I’ve started to translate the AngularFaces showcase to German. I didn’t manage to finish it because I ran out of time. So offering a large part of the Material.css showcase in ten (!) languages is no small feat. To me, that’s a good sign: I don’t think the four team members speak ten languages, so I render it likely that there’s a broad community support for Materialize.css.

Virtually every component you’ll ever need

The other thing that caught my eye is the large list of components. At first glance, everything you need to write a business application seems to be there: input fields, combo boxes, radio buttons, and checkboxes, just to name a few. Check boxes come with a nice twist: they optionally have an “indeterminate” style, which looks very intuitive to me. This makes Materialize.css one of the few UI libraries offering a convincing approach to three-state checkboxes. Another nice twist is the labels of input fields, which may optionally be displayed as watermarks until you enter your input. That’s one of the things difficult to explain but easy to show, so I recommend you follow this link to have a look yourself.

Wrapping it up

I’m big into Bootstrap, but even I have to admit that Google’s material design already has a big impact on the UI market. My crystal ball is currently slightly undecided, but chances are that Material Design is going to be one of the big things in the future of UI. Materialize.css isn’t the only Material Design implementation, but it’s clearly an interesting one.

BootsFaces 0.8.6 has been Released

Fork me on GitHubThis weekend, we’ve published a new version of BootsFaces. Basically, BootsFaces 0.8.6 is not a big deal. It fixes half a dozen bugs. The most annoying bug that has been fixed was compatibility with Internet Explorer.

The other important change is a breaking change correcting another breaking change introduced with BootsFaces 0.8.5. Starting with BootsFaces 0.8.6, the process attribute of AJAX request now is 100% compatible with its PrimeFaces counterpart. We didn’t feel comfortable with introducing a second breaking change within merely two weeks, but at the end of the day compatibility with PrimeFaces was more important. We want you to be able to use PrimeFaces along with BootsFaces, and that means we should try to align our APIs as much as possible.

Another error we’ve fixed was basically caused by our documentation. Until 0.8.1, you could use <b:image /> with both the src attribute and the name attribute. BootsFaces 0.8.5 added the standard JSF resource library, which changed the meaning of name from “ignored” to “points to a file within the resources folder”. This, in turn, broke the application of at least one developer. Since BootsFaces 0.8.6, the src attribute has priority. Plus, we’ve corrected the documentation. Now it doesn’t claim the name attribute was necessary.

There are a few more bugfixes, as you can see in our release notes. If you’ve already adopted BootsFaces 0.8.5, we recommend updating to 0.8.6. If you haven’t, we recommend updating to 0.8.6, too, because the new version contains a lot of improvements and bug fixes. In any case, we don’t expect any migration effort, with the possible exception of the process attribute.

Like always, we’d like to thank everybody who’s reported a bug or a feature request on our bug tracker or on You’ve contributed to the success of BootsFaces, making it an even bigger success story than it already is!

Having said that, there’s only one word left to say:


When Your Framework Gets in Your Way

These days, my framework of choice got spectacularly in my way. Don’t get me wrong: D3.js is a good framework. It was the right tool for the job. But it slowed my progress nonetheless.

You know, I wanted to write a particularly fancy presentation. Everybody knows PowerPoint slides by heart, and even a nifty presentation framework like reveal.js has become boring. But there that nice little framework I always wanted to play with. And there’s this nice interactive sunburst diagram. What about converting it into an interactive presentation? And while we’re at it, why don’t you translate the code to TypeScript?

This turned out to be a stupid idea. Luckily I’m not in a hurry, so I don’t mind, and the result is impressive indeed. But with a tight deadline it had been a disaster.

It’s not the first time I experienced this. Even the best framework comes at a price.
Continue reading

What’s New in BootsFaces 0.8.5?

Fork me on GitHubWhat started as a small bugfix release, ended as a full-blown feature release. If the sheer number of commits is an indicator, the new release is awesome: the previous release counted 599 commits. In the meantime, 240 commits went into the 0.8.5 version, give or take a few. Needless to say, this amounts to a lot of added functionality: 11 new components, countless improvements and – of course – bugfixes. Plus, we’ve migrated the relaxed HTML-like markup style from AngularFaces to BootsFaces.

Continue reading

Let’s Make JavaScript Development Simple Again!

Recently, I’ve grown increasingly uneasy about the current state of JavaScript development. I’m a full-time Java developer who tries to get familiar with JavaScript. Over the years, JavaScript has become a really nifty programming language. There’s hardly anything you can’t do with JavaScript. It’s one of the most exciting areas of development in 2016.

Only… each time I start to read a tutorial about JavaScript, I feel stupid. I know I’m not stupid – at least if it comes to programming – so the explanation must be something different. I freely admit I’m lazy. That’s a valid explanation why I don’t cope with most tutorials.
Continue reading

NewsFlash: Lukas Eder’s JAX Talk And Turing Complete SQL

Did you know SQL is Turing complete? Obviously, it’s not. It’s a purely declarative language. It’s designed with a single purpose in mind: dealing with relational databases.

Surprisingly, modern SQL is Turing complete, indeed. This stunning claim has been proven by David Fetter. He’s also written an example that really blew my hat off. It’s possible to write a SELECT statement drawing a Mandelbrot set.

As I’ve mentioned before, SQL is a purely declarative language. So are HTML and XML. But there’s no way HTML could be Turing complete, so this insight came as a surprise to me. The key to being Turing complete are the window functions offered by most modern SQL databases. These, in turn, allow for recursion, and that’s one of the loopholes allowing a purely declarative language like SQL to sneak into the realm of procedural languages. That’s the same trick that makes PROLOG a Turing complete language.

I got aware of the phenomenon when I attended the great JAX talk of Lukas Eder. Today, he’s published a transcript of his talk, including the slides. Highly recommended!

Dig deeper

10 SQL Tricks That You Didn’t Think Were Possible by Lukas Eder

SQL Is Now Turing Complete
drawing a Mandelbrot set with PostgreSQL 8.4

TypeScript and ES2016 Decorators vs. Java Annotations

Consider this TypeScript snippet. It’s a very simple Angular2 component. It looks almost like a Java class, doesn’t it?

    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>'
export class AppComponent { }

In particular, the @Component looks like a Java annotation. In fact, it plays the some role as a Java annotation. It tells the Angular2 framework that this class is not an ordinary POJO, but something special. It’s a component, one of the building blocks of Angular.

Striking similarity

That’s exactly the same thing I already knew from the Java world. @Named converts a POJO into a CDI bean. Sometimes Java annotations even have the same fancy curly braces syntax:

  @ResourceDependency(library = "bsf", name = "js/datatables.min.js", target = "body"),
  @ResourceDependency(library = "bsf", name = "css/datatables.min.css", target = "head")
public class DataTable extends UIData {}

So why do the JavaScript and TypeScript communities insist on calling their annotations “decorators”?

Decorators decorate!

The answer is simple: Decorators are called decorators because that’s what they are. You can use them as annotations. But in reality, they are function calls. The Angular2 framework contains a function called Component() that takes a function as a parameter and returns another function. The @ of @Component tells TypeScript and EcmaScript 2016 to call the Component() function and to pass it the function after the decorator. Usually decorators are used to add functionality to a function.


Does this ring a bell? Exactly – that’s more or less the same as aspect oriented programming. In fact, AOP is one of the classical use cases of Java annotations. Just think of @transactional. This annotation surrounds a method with the glue code needed to execute it in a transaction. In other words, it adds some code before executing the method (opening a transaction) and it adds code after the method (committing the transaction, or rolling it back).


Making the @ symbol an alternative way to call functions is a very elegant way to implement both static annotations and AOP. Plus, it should be possible to pass variables as additional parameters. In Java, annotations only support constants that can be resolved a compile time, and every once in a while, that’s a nuisance.

In hindsight, it’s hard to understand why the Java team added simple annotations instead of full-blown decorators to Java 5. I suppose they didn’t want to add a complex multi-purpose tool. Annotations can be used for exactly one purpose. They resemble a comment. They rely on a framework to be useful. This framework can be the editor, the compiler or the runtime environment. Only a few years later the JavaScript world showed how useful decorators are.

Can decorators be added to Java?

Sure. Java 8 introduced default methods. So we could define a default method in an annotation class and execute it when the annotated method is called. We’d have to consider a couple of corner cases, though. Annotations can be applied to classes, static fields, class attributes and method parameters. We’d have to define useful semantics for each of these corner cases. But that’s not a big deal.

Wrapping it up

However, I don’t think this will ever happen. Annotations have become such an important part of the Java world it’s unlikely anybody takes the risk. So, for now, we can only marvel at the way the language designers took the syntax of the annotation and converted it into something even more useful. By the way, the flexibility of the JavaScript language allows for some tricks Java developers can only dream of. Only – Java applications tend to be a lot bigger than JavaScript applications, so this dreams would quickly turn into a nightmare. Nonetheless, the article I’ve linked in the “dig deeper” section is very interesting, and it’s full of surprises – at least for a programmer like me spending most of their day in the Java ecosystem.

Dig deeper

Exploring EcmaScript 2016 decorators in detail

Newsflash: Concurrency Explained with Starbucks

It’s hard to get concurrency right! Especially for programmers who try to program it using a low-level language like, say, Java 5. In no time, you’ll run into all kinds of problems like deadlocks, race conditions and synchronization, just to name a few. That’s why I recommend using a language like Scala if you need to leverage the power of all your CPU’s core.

Funny thing is that it’s surprisingly easy to explain concurrency in simple words. This article maps concurrency to a real-world example. Serving coffee to customers is a good example on how to use multithreading to improve performance. Read the full story at This article even explains advanced topics like out-of-order execution and speculative execution. Highly recommended!

Newsflash: How to Reduce Tomcat Startup Time

Modern application servers start very fast, but sometimes you still need more performance. Especially if you’ve got a huge and complex application. Gavin Pickin describes an interesting option on his blog. For some reason, he suggests to add an option that’s already the standard configuration of Tomcat 8 (at least on my machine), but it might be interesting nonetheless.

Thing is, Tomcat scans every Jar file it finds at startup time. This is necessary for frameworks like Servlet 3.0, CDI and JSF, which enable to you add some magic to your application by simply annotating a class. However, many jar files don’t contain such an annotation, so it’s a waste of time to have them scanned. Adding such a library to Tomcat’s skip list gives your application a boost. Especially, if you skip not one, but many library.

Read the full story at Gavin Pickin’s blog.

AngularBeans: A Fresh New Take on AngularJS and JavaEE

I’m proud to have convinced Bessem Hmidi to present his AngularBeans framework at AngularBeans is a fresh, new approach integrating AngularJS with a JavaEE backend and has stirred some attraction in the JavaEE world recently.
Bessem works at “Business & Decision” as a Technical Architect. He is also founder and leader of the “Esprit Tunisian Java user Group” and was a part of the Research & Development program at ESPRIT (Tunisian school of engineering). Bringing over 9 years of working with Java related technologies especially Java EE, he is also a professional course instructor, an educator and an international speaker. Plus, he’s founder of the Tunis conference JUG Day.


The Java ecosystem doesn’t lack of web frameworks. There’s a framework for every taste. No matter if you prefer an action based, component driven, request driven… there’s a framework for everyone.
But at a closer look on what happened those few last years in web development, we will be driven to accept the evidence: it’s the era of single page applications, of client side rendering and of the real-time web. Users have become much more demanding. They don’t put up with a single black-and-white terminal screen any more. They’re familiar with highly responsive, interactive user interfaces which are both more fun and more efficient to use.
Those needs are the sources of countless modern client side JavaScript frameworks such as Ember.js, react.js, meteor.js and of course AngularJS. They all consider the server a “pure” service provider, only responsible for processing and providing data, as opposed to the the classic “dynamic views generator” server. Most – maybe even most – developers consider server-side rendering a thing of the past. From a technical point of view, server-side rendering was inevitable in earlier times, but nowadays browser technology has evolved to a point that allows us to shift both rendering and business logic to the client side1.
Continue reading

  1. Footnote: there are exceptions. Client-side rendering is bad when you’re concerned about you mobile device’s battery life

Newsflash: The Wrong Abstraction

I’ve just read an interesting article of Sandi Metz. I consider it important (and provocative) enough to dedicate a newsflash to Sandi’s article. Basically, my article is a commented link. Mind you, how often did you do stupid things during your working hours just because you valued existing to code high?

That’s a common trap I’ve often watch catching other people (and myself, of course). Like Sandi says,

Existing code exerts a powerful influence. Its very presence argues that it is both correct and necessary.

Existing code tricks you into believing it’s good code

Every once in a while you come across complicated code, and you say by yourself, “whow! Such a sophisticated code! It has to be the essence of wisdom of generations of programmers!” More often than not, it’s just clumsy code generations of programmers contributed to without knowing what they did. It’s really hard to detect such a situation. Because you sometimes the code is complicated because it has to be. You never know.

Don’t be overly respectful!

However, sometimes it’s good not to be afraid of redundant code. Adding the wrong abstraction is worse than suffering from a few duplicated lines of code. Often my team tried to unify objects that are identical in the eye of the stakeholder. Consider the simple example of a mailing address. It’s simple, it’s even standardized by your postal office (and probably the ISO and DIN committees, but I didn’t check). Thing is, when we tried to implement the unified address in my previous company, we started to hear “yes, it’s identical, except for…”.

That’s a surprisingly common example. Trying to merge concepts that are identical – only differing by a small margin – may be the first step to unhappiness.

You can refactor in two directions: back and forth

I’d rather you developed an instinct when to introduce abstractions, and – more important – when to unravel abstractions that already have been introduced in your code base. Refactoring isn’t a one-way road. Most of the time you go forward, but there’s a good reason why you can apply refactoring also the other way round. In fact, the notion of “forward” and “backward” is misleading. We’ve been taught to believe that reducing code duplication is good, which is why we instinctively attribute a direction to refactorings, but that’s s subjective attribution which may be right in most situations and wrong in others.

That said, I recommend you to read Sandi’s article. It’s a fast-paced read that’s clearly worth you attention.

The State of Polyglot Programming in 2016: Mission Impossible?

Once upon a time, they used to say every programmer has to learn a new programming language each year, just to stay in shape. When I mention this to Java programmers, they usually start laughing. What used to be true in the 70s, maybe even in the 80s and the early 90s, has become utterly impossible in 2016. Modern programming ecosystems like JavaEE have reached such a level of complexity that it has become challenging to master a single programming language, let alone a second.

Learning the core language is not the problem

Thing is, it doesn’t suffice to learn the language. That’s easy. Once you’ve learned an object oriented programming language, you’ll quickly be fluent in any other object oriented language. Only shifting to another programming paradigm may give you a hard time. I, for one, have to admit I never managed to wrap my head around PROLOG. It’s not difficult, but it’s so different from what I’m usually doing. My rich experience which is so useful at other times prevents me from being a successful PROLOG programmer. But the vast majority of modern languages follow the procedural paradigm, spiced with object oriented programming or functional programming (and in same cases, both). So there’s not to much a challenge from the language side per se.
Continue reading

Adding Type Inference to Java: Good or Evil?

My previous post raved about the simplicity type inference is going to bring to Java. I love the idea. Java is such a verbose, ceremonious language. Little wonder so many developers prefer dynamically typed languages, which seem to be so much simpler to use until you write a huge enterprise application. Java’s proposed type inference is strongly and statically typed, so it’s going to make life simpler without introducing problems. JEP 286 is good news, indeed!

Type infererence obfuscates types

A fine mess it is, Dave Brosius answered. Consider this code. It’s wrong, but can you spot the error?

public boolean foo(Set<Long> ids) {
    val myId = getId();
    return ids.contains(myId);

In fact, I couldn’t until Dave helped me, providing the solution: getId() returns a String, so the contains method will never find the id.

Well. On the one hand Dave is right: the val keyword obfuscates the fact that we’re talking about a String, so it’s a potential source of confusion. You’ll spot the bug immediately with the Java 8 version of the code:

public boolean foo(Set<Long> ids) {
    String myId = getId();
    return ids.contains(myId);

This source code clearly reveals that we’re comparing Strings with numbers, which is unlikely to work (at least in the Java language). Readability matters!

… but …

On the other hand, the example is all wrong. It’s deliberately misleading. I, for one, was an easy victim because I associated the ID of the code snippet with a database primary key, and my primary keys are always numeric. I prefer to have them generated by a sequence of the database.

Several years ago many developers adopted the UUID as an alternative synthetic primary key. From this perspective, I shouldn’t have been surprised by the fact the getId() returns a String. But then, why don’t we call the method getUUID()? Readability matters!

Another interesting aspect is that JEP 286 has been carefully designed to minimize readability problems. In my eyes it’s too conservative, but Dave sought and found a weak spot of the Java API that doesn’t work well with type inference. Even though Set is a generic type, the contains() method doesn’t care about the type. It simply accepts arbitrary Objects as parameter, allowing us to try to search for a String, even though it should be clear from the context that there are no String in the set.

My personal summary: Granted, you have a point, Dave. Type inference might obfuscate the type, and that’s a bad thing. But if used carefully, this shouldn’t be too much of a problem. I can’t remember someone complaining about type inference with Scala, Kotlin or Ceylon. Well, maybe I’ve heard people complain about Scala type inference. Scala seems to attract very clever guys, who love to write their programs in a very, say, academic way. Scala’s type inference is very sophisticated. Sometimes this leads to very sophisticated Scala programs, and that’s one of the key aspects why Scala never gained traction. The Java enhancement proposal is much more conservative. Probably exactly because of the Scala experience.

By the way, as Phil Webb pointed out, using the val keyword isn’t the real source of the problem. Using the “inline” refactoring causes the same obfuscation problem:

public boolean foo(Set<Long> ids) {
    return ids.contains(getId());

IDEs to the rescue

When I published this article on reddit, the first comment pointed out that sooner or later IDEs are able to display the type of the local variable, even if it is defined as a var or val. That doesn’t solve every readability problem, because most likely the type of the variable is displayed in a tooltip only. In other words: most of the time it is invisible. But certainly even that tooltip will help a lot. In fact, the tooltip is an excellent example of my idea: developers aren’t bothered with technical details all the time, but they can easily look them up when they need them.

Another example of obfuscation

Mark Struberg contributed another potential example of trouble introduced by var and val:

val myValue = a().b().c().d();

Which type does myValue have? What happens when the return type of d() changes? Plus, in real life code, the chain of calls may not be quite as simple. It may be hidden among hundreds of lines, each looking deceptively innocent.

Granted, that’s the sort of things that are going to happen, and it’ll be the source of countless overtime hours. But the real question is: which is worse? Actually, we could even run an experiment to decide on the question of hours of overtime. Does type inference increase the number of extra hours, or does it increase them?

Lessons learned from other languages

Most modern programming languages make use of type inference. There’s a lot of discussion whether static or dynamic typing is useful, but so far, I’ve heard little complains about type inference in strongly and statically typed languages like Scala, C#, Ceylon or Kotlin. I’m sceptic about dynamic typing, but the current JEP 286 is limited to strong and static typing, so judging from the experience of the communities of other programming languages, I suppose adding limited type inference to Java is going to be a success story.

Mind you: the examples of Dave and Mark have been carefully designed to expose the weaknesses of the JEP. That’s good, because they made us aware of a problem we might have missed otherwise. But then, why don’t we rely on the common sense of the programmers? Usually they know how much abstraction they and their working mates can cope with. Adding type inference to Java doesn’t forbid us to use explicit types. So let’s give it a try, and use techniques like code review or pair programming to make sure our code doesn’t get too sophisticated!

Benefits of type inference

During our discussion on Twitter, Phil Webb exclaimed he’s sometimes afraid of extracting a term into a local variable because of the scary type declaration. Well, this rings a bell with me. I often use this particular refactoring to make the code more readable. Extracting a term to a local variable allows us to assign an expressive variable name to the term, and modern JVMs are clever enough to inline the variable automatically again. But if this local variable is drowned by a verbose type declaration, little is won. In this particular example, using val or var might improve readability a lot. More often then not, we aren’t interested in the type of the variable (that’s a technical issue), but we are interested in the role the variable plays (which is a business issue).

That’s the general pattern why type inference may make the Java language more useful. It gives you an option to hide technical stuff when its irrelevant for the reader. As they say, code that’s not there is code you don’t have to understand. It goes without saying that there are corner cases. Sometimes code is so clever it’s so compact it’s difficult to decipher. It’s like learning latin. At school, we used to ponder half an hour just to decipher a single sentence. Obviously, that’s the wrong approach. But if used wisely, type inference may add to the readability of the source code.

Like I said: Readability matters!

JEP 286 addresses Type Inference in a very conservative way

Given that Brian Goetz (or whoever is the author of this particular line) calls type inference a “non-controversial feature”, there’s quite a lot of controversy about the topic. But if you’re afraid of type inference, read the JEP. It’s a fast read – maybe five to ten minutes – and it’s going to make you rest assured. The authors have limited the scope of type inference considerably.

Target typing vs. left-hand-side type inference

In part, that’s due to target typing. The adoption of Lambda Expressions brought target typing to the Java ecosystem. This is also known as right-hand-side type inference, because it adds type inference to the right hand side of assignments. JEP 286 adds type inference to the left hand side of the assignment operator. Obviously, it’s difficult to have both. This might turn out as a problem to Java programmers.

It’s your responsibility!

But then, with power comes responsibility. Type inference doesn’t mean you are forced to convert every type declaration to a var or val declaration. It’s up to you. If you think var is useful, use it. Otherwise, use the traditional approach, which may be as verbose as

Map<Date, Map<Integer, Double>> map 
     = new HashMap<Date, new HashMap<Integer, Double>>();

In my eyes, this is a scary example: you don’t know nothing about the business value the attributes adds to your program. You only know it’s a map, and reading the type declaration, you learn twice it’s a map of maps. Probably it’s better to use val and an expressive identifier:

val interestRateTableByDate 
     = new HashMap<Date, new HashMap<Integer, Double>>();

It’s still a difficult line, but if you’re working in the finance industry, you might at least guess that this is a collections of tables of interest rates (which are different depending how much money you invest). Interest rate are volatile, so you need to add another dimension – the date – to determine the interest rate.

Granted, you can also do this without val, but then the variable name sort of drowns in technical stuff:

Map<Date, Map<Integer, Double>> interestRateTableByDate 
     = new HashMap<Date, new HashMap<Integer, Double>>();

Dig deeper

JEP286 (adding local variable type inference to Java)
Binary builds for JEP 286 (use at own risk – I didn’t check neither for viruses, nor did I try the files myself!)
My previous article on the proposal to add local variable type inference to Java
Lukas Eder on local variable type inference
Pros and cons of JEP 286 by Roy van Rijn