“Scalalified” code vs functional style code

One of the my colleagues said the following about scala (and I completely share his opinion):

It takes significantly more time to write proper code in Scala then in Java, but when it is done right then it looks so cool and precise!”

One comment about it that it has nothing to do with Java. It can be any imperative language. In this post I will share some examples from real code base, which implemented in Scala. And how it could be implemented in a more functional style. I will update the examples as I encounter them.

So the first one is here. Lets say, you implement an utility which accepts input parameters. Below you can find example how you can parse two input parameters. For example, your utility expects host and port.

val host = 
    if (args.isEmpty)
      "localhost"
    else
      args(0)


val port =
    if (args.isEmpty || args.length <= 1)
      8080
    else
      args(1).toInt

Note that the code above uses some nice scala features, like returned value from an “if” statement or type detection (host is String, while, port is Int). But it is implemented in a purely imperative style. That is what I call “scalalified” code.

Is it possible to implement it more elegant in Scala? I am sure it is. For example like this:

  val defaultPort = 8080
  val (host, port) = args match {
      case Array(host, port, _*) => (host, port)
      case Array(host, _*) => (host, defaultPort)
      case _ => ("localhost", defaultPort)
    }

Indeed, pattern matching to the rescue…

To be continued ….

How to unit test static methods?

At the 1st of march I attended Joy of coding conference (joyofcoding.org). It was one of the most interesting conferences I have been so far and quality of the content and percentage of information I find useful was very high.

One of the sessions there was “Testing and refactoring Legacy Code” from Sandro Mancuso. And he shown how you should deal with testing of static methods.

His main argument was that you should not test it. Instead, replace it with testable components and test against them. So frameworks like Powermock which allows you to test static methods, actually is a wrong way of doing it. And there is short example how you can do it more elegant (it is example from me, not the example actually shown by Sandro).

Lets say you have a service which calls repository to persist an entity:

public class Service {       
    public Entity createNewEntity() {
        return Repository.create(new Entity());
    }

    ... some more methods below .....
}

Unfortunately, the imaginary developer for whatever reason made Repository as an utility class containing only static methods. For example, something like following:

public class Repository {
    private static OrmTool orm = new OrmTool();

    public static Entity create(Entity entity) {
        return orm.insert(entity);
    }
    
    .....
}

So what is the problem with such approach? Well, in this case attempt to test Service#createNewEntity method will require entire integration with a Orm tool or/and underlying database. There are two most common solutions I have seen to solve it so far – use powerful framework to mock Repository.create method (powermock, for example). Another way is to configure your Orm to use some test (often inmemory, like, Hsqldb) database.

While both approaches are valid – the first one is very framework specific and the second one is more integration test then unit.

So how Sandro suggests to fix it?

Of course, we write test first!

Lets say we use mockito (my personal preference) as a mocking framework. Then the unit test could look like something following:

public class ServiceTest {
    private Repository repository = mock(Repository.class);
    private Service service = new Service(repository);

    @Test
    public void createsNewEntity() {
        service.createNewEntity();

        verify(repository).insert(eq(new Entity()));
    }
}

So from the test above it is quite clear that what our service should do it is just call to an insert method of a repository.

But wait a second, we do not have “insert” in the Repository utility. Right! That is exactly small and powerful trick Sandro illustrated.

In our situation we would convert utility class Repository to the usual class (component), inject it to the service and add one instance method wich will be just delegate to a static create method. Then our code would look like:

The service with injected repository:

public class Service {
    private Repository repository;

    public Service(Repository repository) {
        this.repository = repository;
    }

    public Entity createNewEntity() {
        return repository.insert(new Entity());
    }
}

Note that we use new method “insert” here. And repository will look like:

public class Repository {
    private static OrmTool orm = new OrmTool();

    public static Entity create(Entity entity) {
        return orm.insert(entity);
    }

    public Entity insert(Entity entity) {
        return Repository.create(entity);
    }

    .....
}

As next step you can do the same trick for the all other calls to the static method and replace them one by one. And when it is done you can just inline it and get rid of it. That’s it!

Pretty simple and obvious, but it is amazing how such simple trick can be overlooked by a lots of developers (including myself).

P.S. Enjoy it and refactor with pleasure!

To use, or not to use…

Recently, I have started use Scala in my daily job actively. And now I have better understanding of all these people who shout that Java sucks. Being big Java  fan for a long time I can’t deny that for some task it is not designed well. More modern languages do the same job much better. This post is just another (there are plenty of them in internet) example, but it comes from real life scenario, so I think it worth to share it.

Let’s say we have a collection of entities in an arbitrary order. And we have list of entities ids. What we want is method that returns list of entities in the same order as provided list of ids. Example, below shows how you can implement it in Java while it still readable and easy to understand:

private List<Entity> sortEntitiesById(Collection<Entity> unsortedEntities, List<Long> ids) {
    Map<Long, Entity> entitiesMappedById = new HashMap<Long, Entity>();
    for (Entity entity : unsortedEntities) {
        entitiesMappedById.put(entity.getId(), entity);
    }

    List<Entity> sortedEntities = new ArrayList<Entity>();
    for (Long id : ids) {
        Entity entity = entitiesMappedById.get(id);
        if (entity != null) {
            sortedEntities.add(entity);
        }
    }
    return sortedEntities;
}

Pretty straightforward code. We create temporary map, where we place entity id as a key and entity itself as value. And then iterate through the list of sorted ids and build result list using newly created map. No rocket science at all. Easy to understand what is going on. And not so difficult to write, isn’t it?

But that’s what all these java haters call boilerplate. Let’s take a look how can you implement it in scala, for example.

def sortEntitiesById(entities: List[Entity], ids: List[Int]) = {
    ids.flatMap(id => entities.find(e => e.id == id))
}

Feel the difference? It is hard to deny that second looks at least much shorter. What about readability then? Well, it is just matter of getting used to language syntax, after all it is much easy to read 3 lines instead of 15.

What about functional libraries which brings you functional style to a Java program, you can ask. Unfortunately, it is far not so elegant as it can be solved in some modern languages. For example, look at Java code with Guava which solves the same problem in a more functional style:

    private List<Entity> sortEntitiesByIds(final List<Entity> entities, final List<Integer> ids) {
        List<Entity> sortedEntities = transform(ids, new Function<Integer, Entity>() {
            @Override
            public Entity apply(final Integer id) {
                return find(entities.iterator(), new Predicate<Entity>() {
                    @Override
                    public boolean apply(Entity entity) {
                        return id == entity.getId();
                    }
                }, null);
            }
        });
        sortedEntities.removeAll(newArrayList((Entity) null));
        return sortedEntities;
    }

From my personal opinion, it looks even worse than purely imperative style from the first example. And that is not because of Guava, which is very nice and useful library. It is because of Java.

Instead of conclusion I would like to share some thoughts. Looking at modern functional and hybrid languages like Haskell or Scala, it is obvious that Java has to adopt features from other languages, and preferably do it as soon as possible. And Oracle engineers are doing great understand it and doing great job. But for developers there is no excuse anymore to work with Java only. Scala, for example, and other JVM based languages solve some tasks in much more elegant and efficient way than Java. I don’t say that we should stop using Java, because for a lot of tasks it still a good and maybe best option. But we should also realize that Java is just another tool. Powerful, stable and mature but just a tool. And if other tools suite better for solving some problem let’s would not be conservative and start use new tools.