July 25, 2011 at 11:15 pm
filed under Coding
Tagged FP, java, javascript, ruby
I’ve been coding lately, and fortunately or unfortunately, it’s Java. I hadn’t done much Java before I started working on this current project; my experience before this was with C++ in college, a bunch of Python, a splash of Ruby, a bunch of JavaScript, and a very small pinch of Objective-C/CocoaTouch.
It’s JavaScript and Ruby that’ve influenced me most lately. Functional patterns in particular have attracted my attention. I really dig stuff like this in Ruby:
open('somefile').readlines.each do |x| print x end |
And then I spent a whole boatload of time in JavaScript, where you get to do stuff like this:
var someArray = [1, 4, 2, 3, 5]; goog.array.forEach(arr, function (e, i, a) { console.log("Here's a number: " + e); }); |
What I really dig about this pattern is passing in a function where I can do whatever I like. The factory pattern becomes much simpler. We can pass this around to whoever:
var url = "/foo"; var reqFactory = function() { var req = new Request(); req.setUrl(url); req.addHeader("baz", "quux"); return req; }; |
The current conundrum involves implementing some kind of retry logic. In one case, I need to build a new request each time the request fails. In another case, I just want to retry for a certain subset of exceptions. In yet another case, if I make the request and it doesn’t have what I want, I want to re-issue it.
In Java, it’s— it’s messy. I don’t know what the Java-esque way of doing it is, quite frankly. I find myself wanting to create a Retrier interface which defines an onSuccess, onFailure, and a doRetry method.
I’m not sure what each method should return; what if I want to be able to return whatever it is that we got from the request? Do I create a wrapper class w/generics? I think this is how it works in the Kingdom of Nouns. The nouns just keep proliferating.
The one thing I think Java has going for it is anonymous inner classes. I feel like the way files and classes proliferate in Java is nuts, and being able to keep the implementation of such as a Retrier close to where it’s used seems like a win. It’s a one-off, right? A whole class & implementation & file devoted to it feels like it’s belaboring the point.
I’m sure at some point I’ll figure it out and/or get used to it. In the meantime, every time I want to add a layer of abstraction, it feels like massive overkill. I almost wrote up code samples for the above but it turned out to be too much effort. I can’t be as glib with it, at least not yet. Oh well.