Is there a case for functional programming?

This is a bit of “stream of consciousness”, so… maybe it’ll make sense, maybe you’ll tell me to lay off the caffeine. 😉

A while back I watched a Clojure discussion in an interview with Stu Halloway. Stu obviously loves Clojure and it might be his hammer with which every problem is looking like a nail, but I’m gonna give him more credit than that.

In the presentation, he said something about “maybe we got it wrong” with how we manage state in applications that resonated and got me thinking… did we? Maybe there’s something to the functional programming idea.

In most web applications today, the idea is to remain as stateless as possible. In most of my applications, we grab a bunch of data from the database, munge it into a object model, then turn around a munge it back into text for display on a web page (or into XML). The biggest benefit I get from the object model is ease of relationship navigation and potentially calculated values via derived properties.

Its a similar story when trying to save data. In this case I’m taking a bunch of text values mapping them into an object (or possibly a graph of objects), doing some calculations, workflow, validations and the mapping it back to the database. There is potentially more value on the “save” side of things, but still in most applications, I’m not sure I get a lot from this. The graph “lives” for only a very brief moment and much of the CPU time is just doing the mapping. In Rails when posting data, if you follow the conventions your parameters map through objects directly into the database by virtue of using the same name. In the basic case, the object is serving as a map of values for an update statement.

There just isn’t much interesting real object behavior going on.

If you think about the interface between the browser and the application server, it is essentially a complex, functional interface. Furthermore, the interaction with the database or downstream services are, again, functional.

Maybe we’re pretending in most cases to have state in 3 places – browser, application, and database, when in fact its actually only relevant in 2 – browser & database. Perhaps we’d be better off using a functional language for solving those problems? Is this where the value lies? Maybe the domain model is really only relevant where state is needed, where the objects (data) comes to rest – I’m thinking the browser in particular. Personally, I got the most benefit from a object model back in the old days of “fat client” programming where the application managed it’s state and I bound my objects directly to the UI elements.

I’m not saying that decomposing data into “objects” is a problem. I’m just beginning to wonder if Object-Oriented languages are the proper tool for the job of “stateless application development”. Is it possible that I’ve been seeing OOP as the hammer by which every problem is a nail?

It might be time to explore Clojure…

Languages Part II

As a follow up to my previous post. The languages are (in order): Java, Groovy, Scala, Ruby, and Python.

I find the Ruby example to be the most readable, however it does use a magic variable ‘ARGF’ to help its readability. What’s surprising to me is how I find Scala not that readable. At least, not that much more readable that Java. Its shorter, so that alone is helpful, However, its a little hard to see Scala as the replacement for Java if its not substantially more readable.

Languages

I found a simple example program done in five languages. I’m not saying which is which (but one is obvious). I find the “new” languages interesting, though none of them seem to be getting significant traction in my circles.

I’m posting this now looking for comments and I’ll have a follow up post soon.

Which example reads best to you?

example 1

    public class LongLines{
       static int MAXLENGTH=70;
       public static void main(String[]args)
             throws Exception{
          for(String arg : args){
             BufferedReader br = new BufferedReader ( new FileReader ( arg ) );
             String line;
             for(int lineNo=0; null != (line=br.readLine()); lineNo++){
                if(line.length()>MAXLENGTH){
                   System.out.println(arg+" line="+lineNo+" chars="+line.length());
                }
             }
          }
       }
    }

example 2

 	def MAXLENGTH = 70
	args.each { filename ->
      new File(filename).eachWithIndex { line, lineNumber ->
        def length = line.size()
        if (length > MAXLENGTH) {
            println "$filename line=$lineNumber chars=$length"
        }
      }
 	}

example 3

    val MAXLENGTH = 70
    def process(filename: String) = 
      for {
        (line, lnum) <- Source.fromFile(filename).getLines.zipWithIndex
        if line.length - 1 > MAXLENGTH
      } println(filename+" line="+(lnum + 1)+"chars="+line.length)

example 4

    MAXLENGTH = 70
    ARGF.each{ |line|
       if line.chomp.length > MAXLENGTH
          puts "#{ARGF.filename} line=#{ARGF.lineno} chars=#{line.length}"
       end

example 5

    MAXLENGTH = 70
    def process(filename):
        for i,line in enumerate(open(filename)):      
            if len(line) > MAXLENGTH:
                print filename, "line=", i+1, "chars=", len(line)
      
    for f in sys.argv:
        process(f)

None of these examples really show the robustness of their perspective languages I’m sure, but I think readability is very important and readable brevity is even more important (especially compared to Java).

New Blog Post coming soon!

Expect to see a new blog post here soon! I wonder what it’ll be… 😉

Off Crutches!

I’m still recovering from my accident.

Last week I saw the doctor and he gave the OK to put weight on my leg. His quote was “I want you walking on it.” Cool! Up to this point I was worried about putting weight on my leg (even though I’d gone down to using only one crutch).

So…. no more crutches for me! Whoohoo!!!

Last week I was walking with a very noticeable limp and moving at a snail’s pace, but this week is much better. I’m still not going to win any races, but it gets better every day.

I still don’t have much flexibility in my ankle. I have about 50% of the range of motion that I have with the other foot and I don’t have any strength to “push off” with that foot.

I started physical therapy this week and have some “homework” to do to stretch that ankle. Things are heading in the right direction!

Speaking of Information Radiators

I mentioned in my previous post that I prefer Information Radiators over digital tools if done right. When Googling for a link to Information Radiators I ran across this article on InfoQ discussing the value of them. Check it out if your interested and share your thoughts in comments!

Atlassian tools for $10 bucks!

Don’t know if you saw this or not, but Atlassian has released a new version of their bug tracking tool JIRA and on top of that, they’re selling each of their products for $10 bucks (so called ‘starter‘ licenses).

I didn’t realize this until now, but they also have an agile project management tool called ‘GreenHopper‘ (which looks a lot like Mingle to me – in fact it looks like ThoughtWorks and Atlassian are duking it out product to product).

The best part is that for $10, you get 10 licenses!

I’ve used JIRA quite a bit and its not bad. I really don’t like any defect tracking software (most of them have a lot of noise for little information). However, JIRA ties in nicely with their build server Bamboo and that is huge. Being able to say what defects went into what build without manually tracking build numbers, subversion revision numbers, release numbers, etc provides a lot of value. It automatically answers the question “what’s in the latest build?”

If they’ve integrated GreenHopper in the same fashion, that would also be huge help.

In general, I’m more of a fan of whiteboards, index cards and information radiators. But, if you have a distributed team, Atlassian’s product suite for 10 bucks is definitely worth evaluating.

It just works!

As I blogged about before for, my Mac is 3 years old and still working great. The only exception is the battery. I’m on my second and it only lasts about 30 minutes. I bought an “advanced” battery from FastMac. Initially it had a nice long life, but after a year and (168 cycles) its almost worthless. I’m not sure I’d go with them again. :-(

Yesterday I stopped by my local Apple Store and purchased a new MacBook Pro to replace my old one (planning to give my wife my existing MacBook Pro).

I unpacked it last night as was a bit disappointed that over a month after OS X 10.6 Snow Leopard was released, it only had OS X 10.5. *sigh* It took almost an hour to upgrade (then apply the patches).

But, here’s the real deal: I have never in my life been able to move/upgrade my system as easily as I did last night.

Instead of this being a week of setting the PCs by each other, copying various files over, entering settings and preferences, realizing I forgot something, downloading patches, etc it took me 3 hours. (well… actually it took me 30 minutes and the laptop 3 hours to copy stuff while I slept :-) ).

I had both Macs connected to my network and fired up the “Migration Assistant” on both Macs. Clicked through a few settings/options and off it went copying my applications, settings and documents.

I didn’t expect it to just work. I expected lots of issues, but I logged in to my new Mac and everything was there. My Dock settings, my applications, my mail, my documents, my desktop wallpaper, passwords, etc all there!!

I couldn’t be happier!!

I’m sure I’ll find some stuff that didn’t get copied, but so far the only thing that isn’t working is VMWare’s Fusion (which has a pretty involved installation program). Its there, but not working. My VM image is there however.

Hats off to the Apple developers for making this “just work”…

3 weeks down – 1 week to go

So… as I wrote about in a previous post, I broke my leg 3 weeks ago.

I’ve been hobbling around on crutches ever since and frankly – its getting old!

The good news is that I’m not in any real pain and things seem to be healing OK. I’m still wondering it’ll be like to walk after my cast is off. I’m not concerned about my broken healing leg as much as I’m concerned about my ankle. Its what hurts when I put weight on that leg. I wonder how long I’ll walk with a noticeable limp. :-(

Today I saw the doctor and he gave me a bit of good news – one week from today I’ll be able to trade in my fiberglass cast for a “walking cast” that I can take off to shower, get dressed, etc. Yeah… besides the crutches, having to wrap my leg each morning in a garbage bag (takes 10 minutes!) is the other thing that’s getting really old.

As of today I’m getting around on one crutch which is a huge improvement as I can actually carry a cup of coffee while I walk (very carefully of course).

Its the little things.

I’ve been spending time with Ruby a bit lately and the more I learn, the more I like it.

One of the simple things that I learned early on is that everything is an expression (including if statements).

That allows you to do things like this:

new_value = if some_flag then calculated_value else default_value end

That’s a bit contrived. You’d probably use the ternary operator instead, but you could have blocks of code or methods executed in each step.

Its not huge, but its still much better than the Java way of:

if (someFlag) {
	newValue = calculatedValue
} else {
	newValue = defaultValue
}

Another simple thing that is huge is that Ruby sees “nil” (aka “null” in Java) as being “false” you can do nil checks elegantly like this:

my_var = some_func_that_might_return_nil(val_to_calc) || "default"

The code will get the value of “default” if the function call returns nil. Again, in Java you’d have something like:

String myVar = someFuncThatMightReturnNull(valToCal);
if (myVar == null) {
	myVar = "default";
}

Again its subtle, but it reads and flows much better to me.

Developer At Large