Monday, December 21, 2015

Make Your Factories Beautiful

Every java programmer worth the name knows about the Factory Pattern. It is a convenient and standardized way to reduce coupling by teaching a component how to fish rather than giving it to them. When working with large systems the pattern does however add a lot of boilerplate code to the system. For every entity you need a number of different factories for producing different implementations of that entity, which is both tiresome and unnecessary to write. This is only one of many new patterns that we have come to use at Speedment.
Here is a typical example where you want a car trader to be able to create instances of the Car interface without knowing the exact implementation.
Car.java
public abstract class Car {
    private final Color color;

    public interface Factory {
        Car make(Color color);
    }

    protected Car(Color color) {
        this.color = color;
    }

    public abstract String getModel();
    public abstract int getPrice();
}
Volvo.java
public final class Volvo extends Car {
    public Volvo(Color color) {
        super(color);
    }

    public String getModel() { return "Volvo"; }
    public int getPrice() { return 10_000; } // USD
}
Tesla.java
public final class Tesla extends Car {
    public Tesla(Color color) {
        super(color);
    }

    public String getModel() { return "Tesla"; }
    public int getPrice() { return 86_000; } // USD
}
VolvoFactory.java
public final class VolvoFactory implements Car.Factory {
    public Car make(Color color) { return new Volvo(color); }
}
TeslaFactory.java
public final class TeslaFactory implements Car.Factory {
    public Car make(Color color) { return new Tesla(color); }
}
CarTrader.java
public final class CarTrader {

    private Car.Factory factory;
    private int cash;

    public void setSupplier(Car.Factory factory) {
        this.factory = factory;
    }

    public Car buyCar(Color color) {
        final Car car = factory.make(color);
        cash += car.getPrice();
        return car;
    }
}
Main.java
    ...
        final CarTrader trader = new CarTrader();
        trader.setSupplier(new VolvoFactory());
        final Car a = trader.buyCar(Color.BLACK);
        final Car b = trader.buyCar(Color.RED);
        trader.setSupplier(new TeslaFactory());
        final Car c = trader.buyCar(Color.WHITE);
    ...
One thing you might not have noticed yet is that most of these components are redundant from Java 8 and up. Since the factory interface might be considered a @FunctionalInterface we don’t need the factories, we can simply specify the constructor of the implementing classes as a method reference!
Car.java
public abstract class Car {
    private final Color color;

    @FunctionalInterface
    public interface Factory {
        Car make(Color color);
    }
}
Main.java
    ...
        trader.setSupplier(Volvo::new);
        trader.setSupplier(Tesla::new);
    ...
Notice that no changes are needed to the implementing classes Volvo and Tesla. Both the factories can now be removed and you are left with a much more concrete system!
(For simple examples such as this, the Factory-interface is not needed at all. You could just as well make CarTrader take a Function<Color, Car>. The advantage of specifying an interface for the factory is that it is both easier to understand and it allows you to change the parameters of the constructor without changing the code that uses the factory.)

Tuesday, December 8, 2015

Streaming over Maps with Java 8

In this article I will show you how Speedment Open Source stream efficiently over standard Java maps, expanding the Stream interface into something called a MapStream! This addition will make it easier to keep your streams concrete and readable even in complex scenarios. Hopefully this will allow you to keep streaming without prematurely collecting the result.

One of the largest features in Java 8 was the ability to stream over collections of objects. By adding the .stream()-method into the Collection interface, every collection in the java language was suddenly expanded with this new ability. Other data structures like the Map-interface, does not implement the method as they are not strictly speaking collections.

The MapStream will take two type parameters, a key and a value. It will also extends the standard Stream interface by specifying Map.Entry<K, V> as type parameter. This will allow us to construct a MapStream directly from any Java map.

public interface MapStream<K, V> extends Stream<Map.Entry<K, V>> {
    ...
}

The concept of polymorphism tells us that a child component may change the return type of an overidden method as long as the new return type is a more concrete implementation of the old return type. We will use this when defining the MapStream interface so that for each chaining operation, a MapStream is returned instead of a Stream.

public interface MapStream<K, V> extends Stream<Map.Entry<K, V>> {

    @Override 
    MapStream<K, V> filter(Predicate<? super Map.Entry<K, V>> predicate);

    @Override 
    MapStream<K, V> distinct();

    @Override
    MapStream<K, V> sorted(Comparator<? super Map.Entry<K, V>> comparator);

    ...
}

Some operations will still need to return an ordinary Stream. If the operation change the type of the streamed element, we can’t ensure that the new type will be a Map.Entry. We can, however, add additional methods for mapping between types with Key-Value pairs.


    @Override
    <R> Stream<R> map(Function<? super Map.Entry<K, V>, ? extends R> mapper);
    
    <R> Stream<R> map(BiFunction<? super K, ? super V, ? extends R> mapper);

In addition to the Function that let the user map from an Entry to something else, he or she can also map from a Key-Value-pair to something else. This is convenient, sure, but we can also add more specific mapping operations now that we are working with pairs of values.


    <R> MapStream<R, V> mapKey(BiFunction<? super K, ? super V, ? extends R> mapper);

    <R> MapStream<K, R> mapValue(BiFunction<? super K, ? super V, ? extends R> mapper);

The difference doesn’t look like much, but the difference is apparent when using the API:


// With MapsStream
final Map<String, List<Long>> map = ...;
MapStream.of(map)
    .mapKey((k, v) -> k + " (" + v.size() + ")")
    .flatMapValue((k, v) -> v.stream())
    .map((k, v) -> k + " >> " + v)
    .forEach(System.out::println);

// Without MapStream
final Map<String, List<Long>> map = ...;
map.entrySet().stream()
    .map(e -> new AbstractMap.SimpleEntry<>(
         e.getKey() + " (" + e.getValue().size() + ")"),
         e.getValue()
    )
    .flatMap(e -> e.getValue().stream()
        .map(v -> new AbstractMap.SimpleEntry<>(e.getKey(), v))
    )
    .map(e -> e.getKey() + " >> " + e.getValue())
    .forEach(System.out::println);

The full implementation of MapStream can be found here. If you are interested in more cool stuff, have a look at the Speedment Github page. Have fun streaming!

Friday, December 4, 2015

Parsing Java 8 Streams Into SQL

When Java 8 was released and people began streaming over all kinds of stuff, it didn’t take long before they started imagining how great it would be if you could work with your databases in the same way. Essentially relational databases are made up of huge chunks of data organized in table-like structures. These structures are ideal for filtering and mapping operations, as can be seen in the SELECT, WHERE and AS statements of the SQL language. What people did at first (me included) was to ask the database for a large set of data and then process that data using the new cool Java 8-streams.

The problem that quickly arose was that the latency alone of moving all the rows from the database to the memory took too much time. The result was that there was not much gain left from working with the data in-memory. Even if you could do really freaking advanced stuff with the new Java 8-tools, the greatness didn’t really apply to database applications because of the performance overhead.

When I began committing to the Speedment Open Source project, we soon realised the potential in using databases the Java 8-way, but we really needed a smart way of handling this performance issue. In this article I will show you how we solved this using a custom delegator for the Stream API to manipulate a stream in the background, optimizing the resulting SQL queries.

Imagine you have a table User in a database on a remote host and you want to print out the name of all users older than 70 years. The Java 8 way of doing this with Speedment would be:

final UserManager users = speedment.managerOf(User.class);
users.stream()
    .filter(User.AGE.greaterThan(70))
    .map(User.NAME.get())
    .forEach(System.out::println);

Seeing this code might give you shivers at first. Will my program download the entire table from the database and filter it in the client? What if I have 100 000 000 users? The network latency would be enough to kill the application! Well, actually no because as I said previously, Speedment analyzes the stream before termination.

Let’s look at what happens behind the scenes. The .stream() method in UserManager returns a custom implementation of the Stream interface that contain all metadata about the stream until the stream is closed. That metadata can be used by the terminating action to optimize the stream. When .forEach is called, this is what the pipeline will look like:

The Java 8 Pipeline

The terminating action (in this case ForEach will then begin to traverse the pipeline backwards to see if it can be optimized. First it comes across a map from a User to a String. Speedment recognise this as a Getter function since the User.NAME field was used to generate it. A Getter can be parsed into SQL, so the terminating action is switched into a Read operation for the NAME column and the map action is removed.

The first intermediate operation is removed

Next off is the .filter action. The filter is also recognised as a custom operation, in this case a predicate. Since it is a custom implementation, it can contain all the necessary metadata required to use it in a SQL query, so it can safely be removed from the stream and appended to the Read operation.

The source of the Java 8 pipeline is reached

When the terminating action now looks up the pipeline, it will find the source of the stream. When the source is reached, the Read operation will be parsed into SQL and submitted to the SQL manager. The resulting Stream<String> will then be terminated using the original .forEach consumer. The generated SQL for the exact code displayed above is:

SELECT `name` FROM `User` WHERE `User`.`age` > 70;

No changes or special operations need to be used in the java code!

This was an simple example of how streams can be simplified before execution by using a custom implementation as done in Speedment. You are welcome to look at the source code and find even better ways to utilize this technology. It really helped us improve the performance of our system and could probably work for any distributed Java-8 scenario.


Until next time!

Friday, October 2, 2015

Generating Multiple Combinations Instead of Typing Them

There is only one thing most programmers hate more than to repetitively type the same code over and over again and that is to try to fix all the bugs that come with that kind of design. A really good principle is DRY ("Don't Repeat Yourself"). But still, with the new functions, optionals, streams and so on that came with Java 8 it is almost impossible to not do it if you want to avoid expensive boxing and unboxing of primitive datatypes into objects. Hopefully this will all be fixed in project Valhalla, but until that is accepted into OpenJDK, we will have to manage in some other way.

In an earlier article I demonstrated an object oriented code generator that we used in the Speedment project. To solve this issue with code repetition regarding primitive and object types, I wrote a small utility class that can be used to get all the different combinations that exist in streams, functions and so on. Here is how it looks when I generate all the 11 possible combinations of a MapAction class:

final Generator gen = new JavaGenerator();
        Formatting.tab("    ");
        
        System.out.println(Variants.allByAll()
            .filter(Variants::checkCompability)
            .map(two -> {
                final File file = File.of(
                    two.getName("com/speedment/steam/action/", "To", "MapAction.java")
                );

                final Type in = Type.of("IN");
                final Type out = Type.of("OUT");

                file.add(Class.of(two.getName("To", "MapAction"))
                    .final_()
                    .call(clazz -> 
                        two.getGenerics("IN", "OUT").forEachOrdered(clazz::add))
                            .add(Type.of("com.speedment.stream.StreamAction")
                            .add(Generic.of().add(two.first().streamType(in)))
                            .add(Generic.of().add(two.second().streamType(out)))
                    )

                    .add(Field.of("mapper", two.asFunction(in, out))
                        .private_().final_()
                    )

                    .call(() -> file
                        .add(Import.of(Type.of(Objects.class))
                            .static_()
                            .setStaticMember("requireNonNull")
                        )
                    )

                    .add(Constructor.of().public_()
                        .add(Field.of("mapper", two.asFunction(in, out)))
                        .add("this.mapper = requireNonNull(mapper);")
                    )

                    .add(Method.of("apply", two.second().streamType(out))
                        .add(OVERRIDE).public_()
                        .add(Field.of("stream", two.first().streamType(in)))
                        .add("return requireNonNull(stream).map(mapper);")
                    )

                ).call(new AutoJavadoc<>());

                return file;
            })
            .map(gen::on)
            .filter(Optional::isPresent)
            .map(Optional::get)
            .collect(joining("\n-------------------------------------------\n"))
        );

When the code is executed it will generate eleven java files and output them to the console. The output of the program can be found here.


Tuesday, July 21, 2015

The terrors of automated json encoding

Suddenly and out of nowhere are all your clients passwords out on the web IN CLEAR TEXT! Huh?! Oh, It was just a nightmare. Or was it? *Spooky voice*

One of the dangers with automation is that computers lack ethics. They will happily do whatever you tell them to, even if it is horrible stuff you didn't really think through. One such thing I encountered recently was a feature that would automatically parse your database entities into JSON. Well, that's nice, isn't it? Less boilerplate code, higher readability, what's not to like? Well, the thing is that one of the many database tables happened to be the Account table and in it was (for some god-damn reason) passwords in plain text! The nightmare was real, for when the corrupt dictator of a system got its hands on the entity it immediately parsed it into JSON and sent it out for the world to see. Well, it didn't really make it to production so no harm done, but it could have. That's the point.

Adding some pepper and salt to the database was quickly fixed, but even if the passwords are salted it would be really stupid to include even hashed passwords in the public API. We needed some way to control what information to include in the JSON parsing and what to put at the bottom of a very big rock. 

The solution I came up with was this:
JsonEncoder imageEncoder = JsonEncoder
    .allOf(images)
    .put(Image.UPLOADER,
        JsonEncoder.allOf(users)
            .remove(User.AVATAR)   // Too large...
            .remove(User.PASSWORD) // Too secret...
        );

String json = imageEncoder.apply(someImage);

A JSON encoder is instantiated using the entity manager. The encoder can then be configured by adding and removing entity fields, even including foreign tables to create a hierarchical view of the domain. When the encoder is setup, entities can be passed to it to produce JSON strings. The code above now produce the following JSON:

{
    'id' : 512,
    'title' : 'A beautiful waterfall',
    'description' : 'Taken in the summer 2013',
    'uploader' : {
        'id' : 57,
        'mail' : 'emil@speedment.com',
        'firstname' : 'Emil',
        'lastname' : 'Forslund'
    },
    'img_data' = '...'
}

The implementation of the JsonEncoder-class can be found in the source code of the Speedment project here. Hopefully this post didn't scare you too much! :)

Wednesday, June 17, 2015

Another view on generated code

This is a follow-up on my last article regarding CodeGen, the object-oriented code generator for java. One of the advantages of the modular approach demonstrated there is that multiple views can be attached to the same generator. By using different "factories", the rendering can go through the same pipeline and still be divided into different contexts.

In this example, we will render the same "concat-method" model using two different installers. One is the standard java-installer and one is an example XML-installer.

The XMLInstaller will have two additional views, MethodXMLView and FieldXMLView. Those views will use some of the Java-views (like TypeView) since a type looks the same in both contexts.

Main.java

public class Main {
    private final static TransformFactory 
        XML = new DefaultTransformFactory("XMLTransformFactory")
            .install(Method.class, MethodXMLView.class)
            .install(Field.class, FieldXMLView.class),

        JAVA = new JavaTransformFactory();

    public static void main(String... args) {
        final Generator gen = new DefaultGenerator(JAVA, XML);
        Formatting.tab("    ");

        gen.on(
            Method.of("concat", DefaultType.STRING).public_()
                .add(Field.of("str1", DefaultType.STRING))
                .add(Field.of("str2", DefaultType.STRING))
                .add("return str1 + str2;")
        ).forEach(code -> {
            System.out.println("-------------------------------------");
            System.out.println("  " + code.getInstaller().getName() + ":");
            System.out.println("-------------------------------------");
            System.out.println(code.getText());
        });
    }
}

MethodXMLView.java

public class MethodXMLView implements Transform<Method, String> {
    @Override
    public Optional<String> render(Generator gen, Method model) {
        return Optional.of(
            "<method name=\"" + model.getName() + "\" type=\"" + 
            gen.on(model.getType()).get() + "\">" + nl() + indent(
                "<params>" + nl() + indent(
                    gen.metaOn(model.getFields())
                        .filter(c -> XML.equals(c.getFactory()))
                        .map(c -> c.getText())
                        .collect(Collectors.joining(nl()))
                ) + nl() + "</params>" + nl() +
                "<code>" + nl() + indent(
                    model.getCode().stream().collect(Collectors.joining(nl()))
                ) + nl() + "</code>"
            ) + nl() + "</methods>"
        );
    }
}

FieldXMLView.java

public class FieldXMLView implements Transform<Field, String> {
    @Override
    public Optional<String> render(Generator gen, Field model) {
        return Optional.of("<field name=\"" + model.getName() + "\" />");
    }
}

Results

When the application above is executed, the following will be outputed:

-------------------------------------
  JavaTransformFactory:
-------------------------------------
public String concat(String str1, String str2) {
    return str1 + str2;
}
-------------------------------------
  XMLTransformFactory:
-------------------------------------
<method name="concat" type="java.lang.String">
    <params>
        <field name="str1" />
        <field name="str2" />
    </params>
    <code>
        return str1 + str2;
    </code>
</methods>

The same model is rendered in two different languages using the same rendering pipeline.

Tuesday, June 2, 2015

Object-Oriented approach to Code Generation

Code Generation is  a common way to reduce the unhealthy load of boring tasks often put on us eager code grunts. Many code generation frameworks I have seen use a template-replace-repeat approach where you write a template for how the generated code file should look and then replace certain keywords and repeat other sections to produce the specific file you want.

A problem with this approach that annoys me is that it is really difficult to know if the generated code will work or not until you compile it. You might have changed the name of one class and suddenly the generated code won't build. To handle this issue I started a project called CodeGen that aim to be completely object-oriented so that you can benefit from type-safety all the way from template to executable code. The main user case for the generator is the Speedment software, but it can be used in a variety of projects.

Consider the following code:
final Generator generator = new JavaGenerator();

final File file = File.of("org/example/Foo.java")
    .add(Class.of("Foo").public_()
        .add(Field.of("x", DOUBLE_PRIMITIVE).final_())
        .add(Field.of("y", DOUBLE_PRIMITIVE).final_())
        .add(Field.of("z", DOUBLE_PRIMITIVE).final_())
        .call(new AutoConstructor())
        .call(new AutoSetGetAdd())
        .call(new AutoEquals())
    )
    .call(new AutoJavadoc())
    .call(new AutoImports(generator))
;

The model tree of the application is built using beans. New methods and member variables can be added to the tree to create variants of the same class.
When the code is to be rendered it can easily be passed to a generator class.
String code = generator.on(file).get();

The generated code will look like the following:
/**
 * Write some documentation here.
 */
package org.example;

import java.util.Optional;

/**
 * @author You name here
 */
public class Foo {

    private final double x;
    private final double y;
    private final double z;

    /**
     * Initializes the Foo component.
     *
     * @param x  the x
     * @param y  the y
     * @param z  the z
     */
    public Foo(double x, double y, double z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    /**
     * Returns the value of x.
     *
     * @return  the value of x
     */
    public double getX() {
        return x;
    }

    /**
     * Sets a new value for x.
     *
     * @param x  the new value of x
     */
    public void setX(double x) {
        this.x = x;
    }

    /**
     * Returns the value of y.
     *
     * @return  the value of y
     */
    public double getY() {
        return y;
    }

    /**
     * Sets a new value for y.
     *
     * @param y  the new value of y
     */
    public void setY(double y) {
        this.y = y;
    }

    /**
     * Returns the value of z.
     *
     * @return  the value of z
     */
    public double getZ() {
        return z;
    }

    /**
     * Sets a new value for z.
     *
     * @param z  the new value of z
     */
    public void setZ(double z) {
        this.z = z;
    }

    /**
     * Generates a hashCode for this object. If any field is
     * changed to another value, the hashCode may be different.
     * Two objects with the same values are guaranteed to have
     * the same hashCode. Two objects with the same hashCode are
     * not guaranteed to have the same hashCode."
     *
     * @return  the hash code
     */
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 31 * hash + (Double.hashCode(this.x));
        hash = 31 * hash + (Double.hashCode(this.y));
        hash = 31 * hash + (Double.hashCode(this.z));
        return hash;
    }

    /**
     * Compares this object with the specified one for equality.
     * The other object must be of the same type and not null for
     * the method to return true.
     *
     * @param other  the object to compare with
     * @return  {@code true} if the objects are equal
     */
    @Override
    public boolean equals(Object other) {
        return Optional.ofNullable(other)
            .filter(o -> getClass().equals(o.getClass()))
            .map(o -> (Foo) o)
            .filter(o -> this.x == o.x)
            .filter(o -> this.y == o.y)
            .filter(o -> this.z == o.z)
            .isPresent();
    }
} 

Every component is implemented as a Interface-Class pair so that you can change the implementation dynamically without rewriting other parts of the system.

Hopefully this will be helpful for other people!

Thursday, May 28, 2015

Lightweight Framework for Tiny Web Services

Some while ago I was sitting on the train with my laptop, half-heartedly coding on some minor side project to make the time pass a little bit faster. I have honestly forgotten what the project was about, but I remember thinking that it would have been so much easier to get a prototype up if I didn't have to mess with all the server mumbo-jumbo.

I usually write most of my web projects on top of NanoHttpd since it is lightweight and is easy to get started with, but after a while I started fantasize about how it could be even easier to use. That was what led me to create ServiceKit.

Imagine you are creating a web app that users can communicate with using a REST api. You have two commands, "register" and "login". They both take an username and a password and should return a status of whether the operation succeeded. The code might look something like this:


public final class LoginProject extends NanoHTTPD {

    @Override
    public Response serve(IHTTPSession session) {
        final Map body = new HashMap<>();
        final NanoHTTPD.Method method = session.getMethod();
        final String uri = session.getUri();
        final String command = uri.substring(uri.indexOf("/") + 1);

        if (Method.PUT.equals(method) || Method.POST.equals(method)) {
            try {
                // Make sure the body is downloaded.
                session.parseBody(body);
            } catch (IOException ex) {
                return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT,
                    "INTERNAL SERVER ERROR: IOException: " + ex.getMessage()
                );
            } catch (ResponseException ex) {
                return new Response(ex.getStatus(), MIME_PLAINTEXT, ex.getMessage());
            }
        }
        
        final Map params = session.getParms();
        final String username = params.get("username");
        final String password = params.get("password");

        final String msg;
        switch (command) {
            case "register":
                if (tryRegister(username, password)) {
                    msg = "{'success':true}";
                } else {
                    msg = "{'success':false,'msg':'Username already taken.'}";
                }
                break;
            case "login":
                if (tryLogin(username, password)) {
                    msg = "{'success':true}";
                } else {
                    msg = "{'success':false,'msg':'Wrong username or password.'}";
                }
                break;
            default:
                msg = "{'success':false,'msg':'Unknown command.'}";
                break;
        }
        
        return new NanoHTTPD.Response(msg);
    }

    ...
    
    public static void main(String... params) {
        ServerRunner.run(LoginProject.class);
    }

    public LoginProject() {
        super (1337);
    }
}

With service kit, the code could be reduced significantly by using annotations to declare new services and automatically parsing in- and output to JSON.


public final class LoginProject extends HttpServer {
    
    @Service({"username", "password"})
    public static Status login(String username, String password) {
        if (tryLogin(username, password)) {
            return Status.success();
        } else {
            return Status.failure("Wrong username or password.");
        }
    }
    
    @Service({"username", "password"})
    public static Status register(String username, String password) {
        if (tryRegister(username, password)) {
            return Status.success();
        } else {
            return Status.failure("Username already taken.");
        }
    }
    
    ...
    
    private static class Status {
        private final boolean success;
        private final String msg;

        private Status(boolean success, String msg) {
            this.success = success;
            this.msg     = msg;
        }

        public static Status success() {
            return new Status(true, "");
        }
        
        public static Status failure(String msg) {
            return new Status(false, msg);
        }
    }
    
    public static void main(String... param) {
        HttpServer.run(LoginProject.class);
    }
    
    public LoginProject() {
        super (1337);
    }
}

ServiceKit uses Googles GSON project for the parsing so no specific interface is required to serialize and deserialize the parameters. That makes the code more readable and prevents bugs related to malformed results etc.

The example above will give you two commands accessible over HTTP like this:
http://example.com/login?username=YourName&password=YourPassword
http://example.com/register?username=YourName&password=YourPassword

The source code for ServiceKit is available here on GitHub! Let me know what you think about this approach!

Tuesday, April 14, 2015

Here are my thought on utility classes

Okey, it is time we sat down and had a talk. Yes, I know it is difficult to find the time, but we really need to have this conversation. We need to agree on some rules regarding utility classes in java.

Quite often when I browse around Github for interesting java projects (yes, I do that, don't judge me..) I find code that looks like this:

public class Foo {
    private final int x, y, z;
    
    public Foo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    ...

    public static Foo doSomethingWith(Foo a, Foo b) {
        ...
    }

    public static Foo doSomethingElseWith(Foo a, Foo b) {
        ...
    }
}

You have a class with a specific purpose and then you add logic that operates on that class as static methods. Here is why this is bad practice:
  1. Your classes will turn out quite long
  2. It is confusing to see Foo.blablabla and foo.blablabla in the same context
  3. The static methods can't be used for anything else than Foo
That's where utility classes enters to picture. If we can agree to put static logic in a separate class and reserve the suffix "Util" for that purpose, we can separate the model from the logic.

public class FooUtil {

    public static Foo doSomethingWith(Foo a, Foo b) {
        ...
    }

    public static Foo doSomethingElseWith(Foo a, Foo b) {
        ...
    }
}

A Template for Utility Classes

The thing now is that we have nothing that prevents us from instantiating, extending or in other ways misuse this new class. Here is a template I usually go for when writing utility classes:

public final class FooUtil {

    public static Foo doSomethingWith(Foo a, Foo b) {
        ...
    }

    public static Foo doSomethingElseWith(Foo a, Foo b) {
        ...
    }

    private FooUtil() {
        throw new RuntimeException(
            "This class is a utility class and should therefore never be instantiated."
        );
    }
}

The exception in the constructor prevents the class from being instantiated using reflection.

Wednesday, April 1, 2015

The First Age... or something

Hello, mysterious internet community! I come in peace!

Whenever I find an interesting new blog I always begin by clicking myself back to the very inception to read the first post made on it. Most texts are some awkward greeting followed by a vague description about what the blog is supposed to be. Others begin by introducing themselves to give the reader some idea of who the author is and why he or she has decided to waste precious weekends and afternoons talking to imaginary friends on the internet. Given this honorable tradition put in stone by my glorious predecessors, I thought to myself, why not?

My name is Emil Forslund and I am an ordinary code grunt working at a software development company in Silicon Valley. On this blog I will try to scoop out some of the overflowing ideas in my head whenever I find the time. It will mostly be about java, I think. Or other crazy IT-stuff.

Okey, I think I have embarrassed myself enough. Back to code grunting.