Boring programmer's notes

Выложен перевод руководства Google Guice

Контейнер внедрения зависимостей Google Guice — это великолепное изделие, которое я вполне успешно применяю на работе. Однако нормальных ресурсов на русском языке по нему почему-то нет.

Некоторое время назад я написал перевод официального мануала по Google Guice для внутреннего пользования. А теперь я наконец-то собрался и выложил его в общий доступ. Может быть, кому-нибудь пригодится.

В переводе присутствует только часть User’s guide с официальной вики. Возможно, если будет время, я переведу и остальные главы оттуда.

Исправления и замечания по переводу приветствуются.

Devourer library first release

27/02/2013

I’m proud to announce the first release of Devourer XML processing library.

Devourer is a library for streaming XML processing. It is heavily inspired by Apache Digester, and does essentially the same job, however, it is different in usage and is completely different inside. It is described in detail in the official guide which appeared on this site earlier. Several examples are present there as well.

There are multiple things I’d like to extend and evolve in the library, so more releases will be coming. Hope it will be useful to someone.

New backend for this site

12/02/2013

Finally, I found time to work on my site again.

It turned out that while I was busy at work and university, Hakyll, a Haskell library for generating static sites (this site is generated by its means), had been upgraded to version 4, which brought a number of changes. I had to tinker with generator script for some time, but the new monadic architecture is way better than the previous one, and now it is much easier to generate complex things like tags, support for which I have added in this site.

If you’re interested, you can find the source of this generator in my Github repo. Maybe I will find another piece of time and make it literal Haskell script embedded in this site.

It slightly bothers me that I’m not writing anything here, but unfortunately I just don’t have time — I’m just near the finish line of my university course, and I have to prepare for the exams and to write my graduation work.

Anyway, if you’re reading this, thanks for your attention.

Builder pattern in Java using static methods

30/09/2012

As you possibly know, Java as a language is not very expressive. However, using its some not very known features it is possible to implement some useful patterns, one of them being builder.

Java users usually understand the following construction under Builder.

SomeComplexObject object =
    new SomeComplexObjectBuilder()
        .setParameter1(x)
        .setParameter2(y)
        .setParameterN(z)
        .build();

However, the builder pattern I’m writing about is more known in Groovy world. It is very easy to implement and use it there. It looks like this (I may be somewhat wrong in Groovy syntax, but this is just to illustrate general idea):

XML xml = buildXML {
    elem "persons" {
        elem "person" {
            attr "name" "Ivan"
            attr "enabled" true
        }
        elem "person" {
            attr "name" "Petr"
            attr "enabled" false
        }
    }
}

It is possible to create something like this in Java. It looks like this:

XML xml = buildXML(
    elem("persons",
        elem("person",
            attr("name", "Ivan"),
            attr("enabled", true)
        ),
        elem("person",
            attr("name", "Petr"),
            attr("enabled", false)
        )
    )
);

Let’s make it. Internal machinery behind this construction is fairly simple. First we define data class, i.e. XML:

package org.example.xmlbuilder;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;

public class XML {
    public final String name;
    public final Map<String, String> attributes = new HashMap<String, String>();
    public final List<XML> children = new ArrayList<XML>();

    public XML(String name) {
        this.name = name;
    }
}

We’re using public final fields here (not standard Java accessors) because the example is very simple, and it is redundant to create getters for final fields (and for setters it is also [almost] impossible).

Now we create a class which will perform the actual work. It looks like this:

package org.example.xmlbuilder;

public final class XMLBuilder {
    private XMLBuilder() {
    }

    public static final class Elem {
        private final XML xml;

        private Elem(XML xml) {
            this.xml = xml;
        }
    }

    public static final class Attr {
        private final String name;
        private final String value;

        private Attr(String name, String value) {
            this.name = name;
            this.value = value;
        }
    }

    public static XML buildXML(Elem root) {
        return root.xml;
    }

    public static Elem elem(String name, Object... objs) {
        XML xml = new XML(name);
        for (Object obj : objs) {
            if (obj instanceof Elem) {
                xml.children.add(((Elem) obj).xml);
            } else if (obj instanceof Attr) {
                Attr au = (Attr) obj;
                xml.attributes.put(au.name, au.value);
            } else {
                throw new IllegalArgumentException("Invalid object supplied: " + obj);
            }
        }
        return new Elem(xml);
    }

    public static Attr attr(String name, Object value) {
        return new Attr(name, value.toString());
    }
}

That’s it. There really are nothing to explain, the code is very simple. There are three static methods, buildXML, elem and attr. elem and attr return intermediate objects (Elem and Attr inner classes) which contain parts of the whole structure, and buildXML returns an actual XML object from the top-level Elem. Maybe only elem body requires attention. It accepts variable number of arguments of different types. You can provide it Elems, which will become child objects, and Attrs, which will set attribute values.

Now, to use it just like in our example above, we have to import static members of XMLBuilder class:

import static org.example.xmlbuilder.XMLBuilder.buildXML;
import static org.example.xmlbuilder.XMLBuilder.elem;
import static org.example.xmlbuilder.XMLBuilder.attr;

...

or, simpler:

import static org.example.xmlbuilder.XMLBuilder.*;

...

Now it is possible to use XMLBuilder’s methods just like if they were static methods in current class (or even global functions, using C++ terms).

I’m absolutely sure that I’m not the first who came up with this idea, but I couldn’t find implementations of such or similar patterns in open source libraries or programs. It is possible that this is so because of performance reasons. Obviously, building an object in this way involves construction of several other objects, and it is certainly quickier to simply invoke constructor.

However, there are not that many extra objects are created, and since they are short-lived, they will be quickly taken out by Java generational garbage collector. I think it is perfectly reasonable to use this approach if you want to get readable code.

First page here

24/09/2012

Hello there. This is my first post at this newly created site.

I didn’t have any kind of blog for a long time; in fact, I didn’t even participated in any kind of social networks. However, recently I’ve started encountering things I would have written about if I had a place for it.

Now I have one, namely this site, and I’ll try and do my best to update it regularly. I sincerely hope that I have something to write that would be useful to someone. In fact, this is my main reason for creating a blog.

Soon I will write several articles, mostly about some quirky problems I had to solve while working on my projects. Turned out that their solutions were surprisingly difficult or even impossible to find on the Internet, so they would be here just in case if someone needed them.

Cheers,

Vladimir Matveev.

Первая страница

24/09/2012

Привет. Это мой первый пост на новом сайте.

У меня долгое время не было никакого блога, и вообще я не участвовал в социальных сетях. Но в последнее время я стал встречать некоторые вещи, о которых я бы написал, если было бы где.

Теперь у меня есть где писать, и я постараюсь обновлять сайт регулярно. Надеюсь, что у меня есть что написать, и это будет кому-то полезно. На самом деле, это основная причина, по которой я завожу блог.

В ближайшее время я, скорее всего, напишу про несколько вещей, которые у меня накопились (в основом, разные неочевидные проблемы, которые мне приходилось решать при разработке программ; их решение на удивление трудно или вообще невозможно было найти в интернете, поэтому, мне кажется, имеет смысл положить их здесь). Ну а дальше видно будет. Писать только я буду больше на английском – это и тренировка языка, и потенциально большая аудитория)

Такие вот дела.