Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, February 23, 2015

Sneaky exceptions

Streams and lambdas are powerfool constructs to facilitate functional style in Java 8. There is a specific inconvenience related to checked exception handling though. I'll illustrate the issue through a simple example: converting a collection of Strings - containing urls - to a collection of URL objects using the Stream API.
List<String> urlStrings = Arrays.asList(
    "http://google.com",
    "http://microsoft.com",
    "http://amazon.com"
);

List<URL> urls = urlStrings.stream().map(URL::new).collect(Collectors.toList());
This would look nice but it won't compile: the constructor of the URL throws a checked exception: MalformedURLException. The map method expects a Function, it's apply method implemented by the lambda expression doesn't declare any checked exceptions:
@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}
Placing the stream operation into a try block or declaring the exception in throws of the method containing it wouldn't help anything - the Function / lambda expression itself won't compile. The only viable option is to handle the exception within the Function. This sacrifices quite a bit of brevity:
List<URL> urls = urlStrings
    .stream()
    .map(url -> {
        try {
            return new URL(url);
        } catch (MalformedURLException e) {
            throw new SomeRuntimeException(e);
        }
    }).collect(Collectors.toList());
Compact code is one thing, the bigger issue is the original exception can't be directly propagated - to be handled outside the stream for instance. There is a pattern that may come handy in such situations: the sneaky throw. The intent is to throw the original checked exception as is, but hide it from the method's signature - effectively imitating characteristics of runtime exceptions. In our case this would be useful for defining Functions that may throw checked exceptions that propagate from the stream operation.

The first step is to define an alternative Function that defines checked exceptions.
public class Sneaky {
    @FunctionalInterface
    public static interface SneakyFunction<T, R> {
        R apply(T t) throws Exception;
    }
    ...
}
This allows us to write lambda expressions identical to normal Functions. It won't be useful in itself, the Stream.map() expects a Function implementation. We need a way to transform our SneakyFunction into a Function.
public class Sneaky {
    @FunctionalInterface
    public static interface SneakyFunction<T, R> {
        R apply(T t) throws Exception;
    }

    public static <T, R> Function<T, R> function(SneakyFunction<T, R> function) {
    ...
 }
}
Type erasure can be used to hide the checked exception from the method signature and make it behave just like a runtime exception.
public class Sneaky {
    @FunctionalInterface
    public static interface SneakyFunction<T, R> {
        R apply(T t) throws Exception;
    }

    public static <T, R> Function<T, R> function(SneakyFunction<T, R> function) {
        return o -> {
            try {
                return function.apply(o);
            } catch (Exception e) {
                Sneaky.<RuntimeException>sneakyException(e);
                return null;
            }
        };
    }

    @SuppressWarnings("unchecked")
    private static <T extends Throwable> T sneakyException(Throwable t) throws T {
        throw (T) t;
    }
}
Transforming SneakyFunction to Function allows checked exception throws in the transformation code:
List<URL> urls = urlStrings.stream().map(Sneaky.function(URL::new)).collect(Collectors.toList());
This code compiles and runs fine, will throw MalformedURLException when needed and it's possible to propagate the exception easily. There are simpler and "safer" solutions for this specific problem of course, that's not the point. The need for propagating checked exceptions from Streams is not uncommon, and this pattern can come handy despite it's controversies. The same pattern may be applied to other functional or pseudo-functional interfaces, like the Consumer. Sneaky throws are used in quite a few libraries, and there are some that support sneaky throws, like Project Lombok.

Friday, January 16, 2015

Functional, fluent JDBC - FluentJdbc

Some projects relying on a relational database do just fine using a high-level ORM, some have need for more low-level control over the queries. Using JDBC directly for application development can be really cumbersome.It's so low-level it's better suited for tool- than application development .
 
There are many abstraction layer libraries over JDBC that add much needed syntax sugar and resource handling safety. Even so, sometimes I find it difficult to find a suitable one for the applications I work on. Either because they constrain in some way or have other unwanted properties (like transitive dependencies).

In some cases I implemented abstractions of my own and a library has started to emerge. I decided to collect those ideas and make it a library for easier reuse. A library that makes the most common SQL querying operations as simple, declarative as possible, is light-weight, has no dependencies. Most similar libraries don't make use of a fluent API which makes way for some interesting possibilities in terms of both readability and flexibility. Also I wanted to support operations that work with large amount of data (streaming, batching).

Some of FluentJdbc 's features: 
  • execution of select/insert/update/delete/alter/... statements as one-liners
  • parameter mapping (named, positional, supporting java.time, Optional, plugins for any types)
  • access to generated keys
  • result -> pojo mapping
  • transaction handling
  • big data (streaming select / batch insert)
Check out FluentJdbc's github page for usage details. The artifact is up in maven central, if you want to give it a shot:
<dependency>
    <groupid>org.codejargon</groupid>
    <artifactid>fluentjdbc</artifactid>
    <version>1.3</version>
</dependency>
Note: java 8 only

Thursday, June 24, 2010

Duck typing in Java

In OO programming duck typing means an object is defined by what it can do, not by what it is. A statement calling a method on an object does not rely on the declared type of an object, only that the object must implement the method called. This concept is a form of inductive reasoning: "when I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck." - James Whitcomb Riley

Several languages advocate it or at least have support for it: Python, Ruby, PHP, C#, etc.. I personally highly prefer static typing for it's better compile-time type safety but duck typing may have justified uses too. The ability to use polymorphism without class inheritence constraints may be handy in certain scenarios. Why not keep that option open in Java too? The idea can be easily illustrated through the following example.

The duck

I expect a duck to be capable of this:
public interface Duck {
    void quack();
}
A few concrete animals (some of them can quack(), but none of them implements the Duck interface):
public class SilentDuck {
    public void quack() {
        System.out.println("quack");
    }
}

public class LoudDuck {
    public void quack() {
        System.out.println("QUACK");
    }
}

public class AverageDog {
    public void bark() {
        System.out.println("bark");
    }
}

public class TalentedDog {
    public void bark() {
        System.out.println("superior bark");
    }

    public void quack() {
        System.out.println("quacklikesound");
    }
}
The expectations

Since SilentDuck, LoudDuck and TalentedDog all can quack(), I should be able to use those objects through the Duck interface - even though their classes don't implement that interface explicitly.
Duck duck1 = attach(Duck.class, new SilentDuck());
Duck duck2 = attach(Duck.class, new LoudDuck());
Duck duckImpersonator = attach(Duck.class, new TalentedDog());

duck1.quack();
duck2.quack();
duckImpersonator.quack();
List<Duck> duck = Arrays.asList(duck1, duck2, duckImpersonator);
AverageDog can't quack(). I expect to get runtime exception when I try to attach it to the Duck interface.
Duck wannabeDuck = attach(Duck.class, new AverageDog()); // throws exception - no quack()
Risks

While duck typing has benefits, it has many drawbacks too. Type checking takes place at runtime instead of compile time. The concrete classes don't refer to a dynamic interface directly, simply renaming a method in them may cause runtime problems in client code unintentionally. Relying on such coding style calls for different, careful practices.

Implementation
I implemented a simple dynamic interface attachment tool to make the above code sample work:
public class DynamicInterface {
    public static <I> I attach(Class<I> i, Object o) {
        try {
            ensureMethodsExist(i, o);
            ensureIsInterface(i);
            return attachInterface(i, o);
        } catch (Exception e) {
            throw new DynamicInterfaceException(e);
        }
    }

    @SuppressWarnings("unchecked")
    private static <I> I attachInterface(Class<I> i, Object o) {
        Object proxy = Proxy.newProxyInstance(i.getClassLoader(), new Class[]{i}, new DynamicInterfaceHandler(o));
        return (I) proxy;
    }

    private static <I> void ensureMethodsExist(Class<I> i, Object o) throws NoSuchMethodException {
        for (Method method : i.getDeclaredMethods()) {
            if (o.getClass().getMethod(method.getName(), method.getParameterTypes()) == null)
                throw new NoSuchMethodException(method.getName());
        }
    }

    private static <I> void ensureIsInterface(Class<I> i) {
        if (!i.isInterface())
            throw new DynamicInterfaceException(i.getName() + " is not an interface");
    }
}

class DynamicInterfaceHandler implements InvocationHandler {
    private Object o;

    DynamicInterfaceHandler(Object o) {
        this.o = o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Method oMethod = o.getClass().getMethod(method.getName(), method.getParameterTypes());
        return oMethod.invoke(o, args);
    }
}

public class DynamicInterfaceException extends RuntimeException {
    public DynamicInterfaceException(Throwable t) {
        super(t);
    }

    public DynamicInterfaceException(String m) {
        super(m);
    }
}