Avoid String Concatenation

  • 518 words
  • two minutes to read
  • comments

This is "string concatenation", and it is a bad practice:

// bad practice, don't reuse!
String text = "Hello, " + name + "!";

Why? Some may say that it is slow, mostly because parts of the resulting string are copied multiple times. Indeed, on every + operator, String class allocates a new block in memory and copies everything it has into it; plus a suffix being concatenated. This is true, but this is not the point here.

Objects Should Be Immutable

  • 1224 words
  • five minutes to read
  • comments

In object-oriented programming, an object is immutable if its state can't be modified after it is created.

In Java, a good example of an immutable object is String. Once created, we can't modify its state. We can request that it creates new strings, but its own state will never change.

However, there are not so many immutable classes in JDK. Take, for example, class Date. It is possible to modify its state using setTime().

I don't know why the JDK designers decided to make these two very similar classes differently. However, I believe that the design of a mutable Date has many flaws, while the immutable String is much more in the spirit of the object-oriented paradigm.

Moreover, I think that all classes should be immutable in a perfect object-oriented world. Unfortunately, sometimes, it is technically not possible due to limitations in JVM. Nevertheless, we should always aim for the best.

This is an incomplete list of arguments in favor of immutability:

  • immutable objects are simpler to construct, test, and use
  • truly immutable objects are always thread-safe
  • they help to avoid temporal coupling
  • their usage is side-effect free (no defensive copies)
  • identity mutability problem is avoided
  • they always have failure atomicity
  • they are much easier to cache
  • they prevent NULL references, which are bad

Let's discuss the most important arguments one by one.

Java Method Logging with AOP and Annotations

  • 989 words
  • four minutes to read
  • comments

Sometimes, I want to log (through slf4j and log4j) every execution of a method, seeing what arguments it receives, what it returns and how much time every execution takes. This is how I'm doing it, with help of AspectJ, jcabi-aspects and Java 6 annotations:

public class Foo {
  public int power(int x, int p) {
    return Math.pow(x, p);

This is what I see in log4j output:

[INFO] com.example.Foo #power(2, 10): 1024 in 12μs
[INFO] com.example.Foo #power(3, 3): 27 in 4μs

Nice, isn't it? Now, let's see how it works.

Object-Oriented Java Adapter of Amazon S3 SDK

  • 556 words
  • three minutes to read
  • comments

I'm a big fan of Amazon Web Services (AWS). I'm using them in almost all of my projects. One of their most popular services is Simple Storage Service (S3). It is a storage for binary objects (files) with unique names, accessible through HTTP or RESTful API.

Using S3 is very simple. You create a "bucket" with a unique name, upload your "object" into the bucket through their web interface or through RESTful API, and then download it again (either through HTTP or the API.)

Amazon ships the Java SDK that wraps their RESTful API. However, this SDK is not object-oriented at all. It is purely imperative and procedural—it just mirrors the API.

For example, in order to download an existing object doc.txt from bucket test-1, you have to do something like this:

AWSCredentials creds = new BasicAWSCredentials(key, secret);
AmazonS3 aws = new AmazonS3Client(creds);
S3Object obj = aws.getObject(
  new GetObjectRequest("test-1", "doc.txt")
InputStream input = obj.getObjectContent();
String content = IOUtils.toString(input, "UTF-8");

As always, procedural programming has its inevitable disadvantages. To overcome them all, I designed jcabi-s3, which is a small object-oriented adapter for Amazon SDK. This is how the same object-reading task can be accomplished with jcabi-s3:

Region region = new Region.Simple(key, secret);
Bucket bucket = region.bucket("test-1");
Ocket ocket = bucket.ocket("doc.txt");
String content = new Ocket.Text(ocket).read();

Why is this approach better? Well, there are a number of obvious advantages.

Get Rid of Java Static Loggers

  • 148 words
  • a minute to read
  • comments

This is a very common practice in Java (using LoggerFactory from slf4j):

import org.slf4j.LoggerFactory;
public class Foo {
  private static final Logger LOGGER =
  public void save(String file) {
    // save the file
    if (Foo.LOGGER.isInfoEnabled()) {
      Foo.LOGGER.info("file {} saved successfuly", file);

What's wrong with it? Code duplication.

MySQL Maven Plugin

  • 577 words
  • three minutes to read
  • comments

I was using MySQL in a few Java web projects and found out there was no Maven plugin that would help me to test my DAO classes against a real MySQL server. There are plenty of mechanisms to mock a database persistence layer both in memory and on disc. However, it is always good to make sure that your classes are tested against a database identical to the one you have in production environment.


I've created my own Maven plugin, jcabi-mysql-maven-plugin, that does exactly two things: starts a MySQL server on pre-integration-test phase and shuts it down on post-integration-test.

Atomic Counters at Stateful.co

  • 360 words
  • two minutes to read
  • comments

Amazon DynamoDB is a great NoSQL cloud database. It is cheap, highly reliable and rather powerful. I'm using it in many web systems.

There is one feature that it lacks, though—auto-increment attributes.

Say that you have a table with a list of messages:

| id   | Attributes                 |
| 205  | author="jeff", text="..."  |
| 206  | author="bob", text="..."   |
| 207  | author="alice", text="..." |

Every time you add a new item to the table, a new value of id has to be set. And this has to be done with concurrency in mind. SQL databases like PostgreSQL, Oracle, MySQL and others support auto-increment features. When you add a new record to the table, the value of the primary key is omitted and the server retrieves the next one automatically. If a number of INSERT requests arrive at the same time the server guarantees that the numbers won't be duplicated.

However, DynamoDB doesn't have this feature. Instead, DynamoDB has Atomic Counters and Conditional Updates, which are very similar features. Still, they're not exactly the same.

In case of an atomic counter, you should create a supplementary table and keep the latest value of id in it.

In case of conditional updates, you should retry a few times in case of collisions.


To make life easier in a few of my applications, I created a simple web service—stateful.co. It provides a simple atomic counter feature through its RESTful API.

Object-Oriented GitHub API

  • 503 words
  • two minutes to read
  • comments

GitHub is an awesome platform for maintaining Git sources and tracking project issues. I moved all my projects (both private and public) to GitHub about three years ago and have no regrets. Moreover, GitHub gives access to almost all of its features through RESTful JSON API.

There are a few Java SDK-s that wrap and expose the API. I tried to use them, but faced a number of issues:

  • They are not really object-oriented (even though one of them has a description that says it is)
  • They are not based on JSR-353 (JSON Java API)
  • They provide no mocking instruments
  • They don't cover the entire API and can't be extended

Keeping in mind all those drawbacks, I created my own library—jcabi-github. Let's look at its most important advantages.

Why NULL is Bad?

  • 973 words
  • four minutes to read
  • comments

A simple example of NULL usage in Java:

public Employee getByName(String name) {
  int id = database.find(name);
  if (id == 0) {
    return null;
  return new Employee(id);

What is wrong with this method?

OOP Alternative to Utility Classes

  • 704 words
  • three minutes to read
  • comments

A utility class (aka helper class) is a "structure" that has only static methods and encapsulates no state. StringUtils, IOUtils, FileUtils from Apache Commons; Iterables and Iterators from Guava, and Files from JDK7 are perfect examples of utility classes.

This design idea is very popular in the Java world (as well as C#, Ruby, etc.) because utility classes provide common functionality used everywhere.

Here, we want to follow the DRY principle and avoid duplication. Therefore, we place common code blocks into utility classes and reuse them when necessary:

// This is a terrible design, don't reuse
public class NumberUtils {
  public static int max(int a, int b) {
    return a > b ? a : b;

Indeed, this a very convenient technique!?