Saturday, November 22, 2014

Opening and closing resources

It's the silliest thing that's been bothering me for agest: why on earth would someone go through all the trouble to write code like that:

InputStream in = null;
try {
    in = openInputStream();
    // do something with in
} finally {
    if (in != null) {
        in.close();
    }
}

First of all, if opening a stream didn't succeed then an exception is thrown and "in" is going to be as null as it gets - that's true, but the actual exception is going to get propagated upwards too - so why the hell do the it in the try block and check for null in finally? It's just so pointless I can't stand it..

InputStream in = openInputStream();
try {
    // do something with in
} finally {
    in.close();
}

Now isn't that a lot more readable, simpler and everything? If the opening of a stream blows up everything blows up too - just like in the code above.

Can anyone please be kind and explain this complete insanity to me?

Sure, with Java 7 we have the try-with-resources feature - but is it doing anything more than the second form?

try (InputStream in = openInputStream()) {
    // do something with in
}

The visibility of the stream is limited to the body of the try statement which seems to be the absolutely only difference to the previous version (the pre-java7 one).

Thursday, November 20, 2014

JSON RPC framework in 12 lines

There are lots of times when I just shake my head in admiration of what Groovy actually is. This has been one of the times today and I'm here to tell you I'm not easily impressed.

We're introducing a communication layer between our microservices based on JSON-RPC (just because it's cool and fast). Here's an initial implementation of a Groovy-based framework for doing JSON-RPC calls:

class JsonRpcClient extends HTTPBuilder {
    JsonRpcClient(String uri) {
        super(uri)
    }

    def methodMissing(String name, args) {
        def result
        request(POST, JSON) { req ->
            body = [ 
                "jsonrpc" : "2.0", 
                "method" : name, 
                "params" : args, "id" : 1 ]
            response.success = { resp, json ->  result = json }
        }
        return result
    }
}

I means sure it's not complete but using it is very much possible!

def http = new JsonRpcClient('http://localhost:8080/example/api/hello')
println http.sayHello("John")

I mean how cool is that, ha? Some meta programming with an existing framework (HTTPBuilder) and you get a micro implementation of JSON-RPC protocol in a few lines of code!

Happy coding! Groovy Rulez!