Feed aggregator

Why InputStream Design Is Wrong

Javalobby Syndicated Feed - Wed, 11-May-16 04:03

It's not just about InputSteam, this class is a good example of a bad design. I'm talking about three overloaded methods read(). I've mentioned this problem in Section 2.9 of Elegant Objects. In a few words, I strongly believe that interfaces must be "functionality poor." InputStream should have been an interface in the first place and it should have had a single method read(byte[]). Then if its authors wanted to give us extra functionality, they should have created supplementary "smart" classes.

        A Serious Man (2009) by Coen Brothers         A Serious Man (2009) by Coen Brothers          

This is how it looks now: 

Categories: Java

A JavaFX HelloWorld Using Java 9’s Project Jigsaw in 60 Seconds

Javalobby Syndicated Feed - Wed, 11-May-16 03:54

By now you’ve probably have heard of Java 9’s new module system a.k.a. project Jigsaw. If you don’t know about Java 9’s new module system, you should visit Mark Reinhold’s paper on The State of the Module System. Also, you should check out @nipafx Nicolai Parlog’s excellent blog at http://blog.codefx.org There he goes into great detail about Java 9’s new module system and many scenarios.

In this article I will attempt to show you how to create a JavaFX Helloworld application using Java 9’s module system in 60 seconds.

Categories: Java

Singletons Are Fine

Javalobby Syndicated Feed - Wed, 11-May-16 00:49

This one’s gonna be short. Honestly, I don’t know how last week’s article about static methods went so long.

Singletons get a bad rap, being called Anti-patterns, and for good reason. The biggest reason given against Singletons is that they’re global state, which is bad. If you want a stateful “Singleton”, there are ways to restrict the application to only having a single instance, even if the class can have multiple instances. While this still largely equates to global state, at least it opens up the possibility of test doubles and makes the “Singleton” itself that much easier to test.

Categories: Java

Scatter-Gather Using Spring Reactor Core

Javalobby Syndicated Feed - Tue, 10-May-16 23:56

I have had a good working experience using the Netflix Rx-Java libraries and have previously blogged about using Rx-Java and Java 8 CompletableFuture for scatter-gather kind of problems. Here I want to explore applying the same pattern using the Spring Reactor Core library.

If you are familiar with Netflix Rx-Java, you already know Spring Reactor Core. The API's map beautifully, and I was thrilled to see that the Spring Reactor team has diligently used Marble diagrams in their Javadoc API's

Categories: Java

Spring AMPQ 1.6.0 Release Candidate (and 1.5.6) Available

Javalobby Syndicated Feed - Tue, 10-May-16 05:47

We are pleased to announce that the Spring AMQP 1.6 release candidate (1.6.0.RC1) is now available in the spring milestone repo.

The 1.5.6 maintenance release is also available with a few bug fixes.

Categories: Java

Scalaz Features for Everyday Usage Part 1: Typeclasses and Scala Extensions

Javalobby Syndicated Feed - Tue, 10-May-16 05:16

Zone: Java

Most of you have probably heard of the great JavaScript book, JavaScript: The Good Parts. In the same light I'd like to show some things from Scalaz which are really great to use in everyday projects, without having to dive into the (at least for me) scary inner workings of Scalaz. For this first part we'll dive into a number of useful typeclasses. In future parts we'll look at stuff like Monad Transformers, Free Monads, Validation etc.

Categories: Java

OO Design Is More About ‘Doing’ Than ‘Being’

Javalobby Syndicated Feed - Tue, 10-May-16 04:31

One of the most profound insights I have learned about OO is that class design—the shaping of classes & types—is best informed by what processing needs to do, rather than the ‘kind’ of entities it goes between.

What we are talking about here is behavior, rather than trying to categorize entities at rest. Program code only acts by being executed; classes & interfaces (types) are a mechanism to dispatch that execution to specific methods.

Categories: Java

Restful Java Metering by Dropwizard Metrics

Javalobby Syndicated Feed - Tue, 10-May-16 04:01

We saw how we can do the restful Java Metering using Jersey event listeners (Read here) in one of our earlier article.

Here we are going to see how to use Dropwizard Metrics framework to do the metering of our restful resource methods. Dropwizard Metrics is using Jersey events listeners internally to achieve this. They have provided nice wrapper and lots of plug-in to gather the performance of each resource methods without much effort.

Categories: Java

Gson: Deserialization of Generic Types

Javalobby Syndicated Feed - Tue, 10-May-16 02:31

Let's imagine that we are developing a wrapper library for an API, which returns JSON documents as a response. And there are many endpoints that have similar structures, except some fragment and may have a different structure. 

Let's go ahead with a simple example. This is what some personal data could look like:

Categories: Java

Is Polyglot Programming Practical?

Javalobby Syndicated Feed - Mon, 09-May-16 23:01

I recently received an email from a well-known consulting firm that said, in essence, “You're a polyglot programmer, we're looking for those, let's talk.”

I can see where they got that impression. In the last three years, I've worked with Java, JavaScript, Scala, Ruby, Python, Clojure, and SQL. In my 30+ year career, I've worked with over 15 languages. And there are a half-dozen more that I haven't used professionally. But why would a recruiter look for that?

Categories: Java

Hazelcast Continuous Query Using C++ Client

Javalobby Syndicated Feed - Mon, 09-May-16 21:01

I am happy to announce that we now added the Continuous Query capability to C++ client with the release of our Hazelcast C++ client version 3.6.2.

It is now possible to register an entry listener for a Map that will be triggered only when the specific Map entries that you choose are affected. This allows you to do more optimal queries.

Categories: Java

Reducing boilerplate code with Project Lombok

codecentric Blog - Mon, 09-May-16 09:02

It’s not a secret that Java is quite verbose and will require a developer to often write significantly more code for the same task than other languages. To address this problem, we’ve mentioned a library called Lombok on the codecentric blog in the past – see here and here. In short, it’s a code generation library that provides a set of annotations you can use to drastically reduce boilerplate code in your applications. I’ve personally used it with great success on a number of occasions and since the topic came up in my current project I wanted to elaborate on it bit more and address a few problems I was confronted with. As we’ve covered the basics before, let me get right to a few specific features and topics that I find noteworthy on top of that.

Using @Builder

For some time now, Lombok provides an annotation for implementing the Builder pattern on your classes. Doing this manually is a good example of Java’s verbosity:

public class Person {
  private String firstname;
  private String lastname;
  private String email;
  public static Builder builder() {
    return new Builder();
  public static class Builder {
    private String firstname;
    private String lastname;
    private String email;
    public Builder fistname(String firstname) {
      this.firstname = firstname;
      return this;
    public Builder lastname(String lastname) {
      this.lastname = lastname;
      return this;
    public Builder email(String email) {
      this.email = email;
      return this;
    public Person build() {
      return new Person(firstname, lastname, email);

With every additional property this code will grow significantly. There’s more sophisticated builder implementations that will for example guarantee that mandatory values are set during the construction of an object, but in my experience, most implementations of the builder pattern look like my example above. Let’s see how Lombok helps:

public class Person {
  private final String firstname;
  private final String lastname;
  private final String email;

That’s it! One line and you have the same implementation as shown before. There’s some parameters that you can use to customize the generated builder. @Builder(toBuilder=true) will generate a toBuilder() method that will copy the contents of an existent Person instance to a builder, for example. That’s useful if you want to copy and change an object.

Other libraries have been doing builder generation before Lombok, but I know of none that integrate as smoothly. PojoBuilder – for example – will create seperate class files in a folder that you have to add to your project’s classpath. In contrast, Lombok hooks into the compile phase and will change the abstract syntax tree of the target class itself.

As with anything, the example case above looks intriguing but once you start working seriously, you often encounter edge cases and all kinds of problems. Generally, my experience has been very positive, but when working with the @Builder pattern I actually had a few problems to solve.

@Builder and generics

When I first put @Builder on a generic class I was confronted with a compiler error.

public class Response {
  private T body;
Response<String> response = Response.builder().body("body").build();

The compiler complains about an incompatible assignment, as the result of the build process is Response<Object>. What’s required is a hint for the compiler when creating the builder, you’ll have to specify the requested type explicitly when creating the builder:

Response<String> response = Response.<String>builder().body("body").build();

@Builder and inheritance

Sometimes you use @Builder on a class that inherits from a parent class. Lombok will not consider fields from the superclass in the generated builder class. There’s a workaround, though. Normally, you use @Builder as a type annotation, but you can also use it on constructors and methods. What you can do in this case is create a constructor that takes all the arguments that are required for your class (including the ones for the superclass) and then place @Builder on the constructor.

public class Parent {
  private String a;
public class Child extends Parent {
  private String b;
  public Child(String a, String b){
    this.b = b;

You’ll get a complete builder and can use it like this:


Lombok and constructor injection

In the context of dependency injection I like to use constructors to pass dependencies into objects: I find it unreasonable to create incomplete objects and to have dependencies set afterwards. In order to use constructor injection, you often have to be able to annotate a constructor. How do you do this if you have Lombok generate your constructors? It turns out, there is an experimental feature that can help you with this:

@AllArgsConstructor(onConstructor = @__(@Autowired) )
public class HelloLombok {
  public Dependency dependency;

Lombok will then add the provided annotation to the generated constructor. You’re right, the syntax looks a bit funny (see the small print at the bottom of the feature documentation for details). And because of the way it is implemented Lombok makes it clear, that this is experimental and might change or disappear in the future. If you can live with that, than it will enable you to combine Lombok and constructor injection (as well as a few other things). If not, you can always choose to not use Lombok for these constructors, of course.

Integrating Lombok

Integrating Lombok into your project is quite easy: For one thing, you need to have Lombok on the project’s classpath in order to get a build working. But equally important is integration with your IDE. I’ve been using both Eclipse and Intellij when working with Lombok, but there are other integrations as well. Again, the Lombok website gives a good overview about what has to be done: For Eclipse, you run the Lombok jar as a java application and tell it about the location of your Eclipse installation, for Intellij there’s a Plugin that you can install via the plugin repository.

The best code that you can write is the code that you don’t write. Lombok is tremendously useful, it will help you to trim your codebase and focus on the important parts of your applications. I’ve been using it for a few years now and I have not experienced any real problems, so far. I recommend you try it yourself!

The post Reducing boilerplate code with Project Lombok appeared first on codecentric Blog.

Categories: Agile, Java, TDD & BDD

Mixin Class Composition in Scala

Javalobby Syndicated Feed - Mon, 09-May-16 04:01

As opposed to languages that only support single inheritance, Scala has a more general notion of class reuse. Scala makes it possible to reuse the new member definitions of a class (i.e. the delta in relationship to the superclass) in the definition of a new class.

Abstract Class

  abstract class AbsInfo {    
    def isSpecialTrain: Boolean

Trait Object

  trait MyTrain {
    def printTrainInfo = {
      println("Train Number : 12675")
      println("Train Name : KOVAI EXPRESS")

Normal Class

  class GeneralQuota {
    def printQuotaDetail = println("General Quota")

Abstract Class With Interface Method Implementation

  class TatkalQuota extends AbsInfo {
    def printQuotaDetail = println("Tatkal Quota")
    def isSpecialTrain:Boolean = false

Mixin Class Composition

  class LadiesQuota extends AbsInfo with MyTrain {
    def printQuotaDetail = println("Ladies Quota")
    def isSpecialTrain:Boolean = false

The LadiesQuota class is constructed from a mixin composition of the parents AbsInfo and MyTrain with the keyword with. The first parent is called the abstract class of LadiesQuotaclass, whereas the second (and every other, if present) parent is called a mixin.

Categories: Java

Code Generation and Templating Made Really Easy

Javalobby Syndicated Feed - Mon, 09-May-16 02:31

Templates are pre-compiled during automatic build of the IDE into so-called template beans (POJOs). By design, application logic is written in user-defined Java code which uses template beans for the data insertion process. Each template bean can render its contents to a text string by simply calling the toString()-method. If previously generated source files have to be updated, the code generation framework also offers support for protected regions which leave manually written text regions unchanged. 

In the following, we list some of its features and continue with a quick introduction.

Categories: Java

JDeps: Simple Dependency Analysis

Javalobby Syndicated Feed - Mon, 09-May-16 00:23

In Java 8 we have a new command line tool called jdeps to know the Java dependencies. It is a nice tool to do static analysis and find out the .class/jar dependencies.

For example, I have a class and wanted to know the dependencies summary as DOT (graph description language) format I can get it by issuing the below jdeps command.

Categories: Java

What's New in the First Open Source CUBA Platform Release?

Javalobby Syndicated Feed - Sun, 08-May-16 21:31

We are proud to announce the general availability of new versions of the CUBA Platform and Studio.

The major update is the new licensing policy: the main part of the platform is now open source under the Apache 2.0 license, the optional components such as BPM, Charts and Maps, Reporting and Full-Text Search are available by per-developer subscription. The CUBA Studio is free for small projects with up to 10 entities and requires the subscription for bigger projects.

Categories: Java

Object Behavior Must Not Be Configurable

Javalobby Syndicated Feed - Sun, 08-May-16 02:31

Using object properties as configuration parameters is a very common mistake we keep making mostly because our objects are mutable—we configure them. We change their behavior by injecting parameters or even entire settings/configuration objects into them. Do I have to say that it's abusive and disrespectful from a philosophical point of view? I can, but let's take a look at it from a practical perspective.

Let's say there is a class that is supposed to read a web page and return its content:

Categories: Java

An Intro to Java 8 Default Interfaces

Javalobby Syndicated Feed - Sat, 07-May-16 23:01

In this article we will explore the Java 8 default method’s feature in interfaces. The Java 8 says “Default methods enable new functionality to be added to the interfaces in libraries and ensure binary compatibility with code written for older versions of those interfaces”.

As Java evolved over the years, the interfaces introduced in the Java library require adding new functionality. If you add new methods in the interface without having default methods feature, all the classes that already implemented the interfaces should undergo a change. This results in changing thousands of lines of code. To avoid this, the Java 8 introduced the default method feature. That is, if you want to add any functionality to the existing interface, you can add it by using the default method feature without affecting the implementations.

Categories: Java

A Few Thoughts About Kotlin and Why I Like It So Much

Javalobby Syndicated Feed - Fri, 06-May-16 23:01

It doesn't matter how many languages you have learned, learning yet another one is always a wonderful experience. I have been working for a couple of months with Kotlin. Have got one app to ready for production state and another in the works.

To cut to the chase, I am really impressed by this language. As in really really impressed. And so I decided that I should write a few posts that can help readers get a better idea and learn about this language. So I started writing out the series and am already onto the third post now. But as I was writing it, I realized what I was writing was really about the mechanics of the language. Not so much about its spirit. Because when one gets into the tactical nitty-gritty details, one tends to miss the forest for the trees. So I decided to pen that here before I start that series (next week), and here are my few thoughts about why I really enjoy the language.

Categories: Java

Testing Improvements in Spring Boot 1.4

Javalobby Syndicated Feed - Fri, 06-May-16 21:31

One of the nice things about working for Pivotal is that they have a great agile development division called Pivotal Labs. The teams within Labs are big proponents of Lean and XP software methodologies such as pair programming and test-driven development. Their love of testing has had a particular impact on Spring Boot 1.4 as we’ve started to get great feedback on things that could be improved. This blog post highlights some of the new testing features that have just landed in the latest M2 release.

Testing Without Spring

The easiest way to unit test any Spring @Component is to not involve Spring at all! It’s always best to try and structure your code so that classes can be instantiated and tested directly. Usually that boils down to a few things:

Categories: Java

Thread Slivers eBook at Amazon

Syndicate content