Thursday, March 29, 2012

Play and Heroku

I've been messing around with Play, and decided that I'd push it up to Heroku based on the tutorial and things I've heard about Heroku.

I'm going to expand on this later but, if you forget the Procfile when deploying your Play application, it may cause your app to get totally jammed and never be able to start.  I spent the next hour or two trying to figure out why my app wouldn't start, even after I'd put the Procfile in.

I solved the problem by deleting my app on Heroku and creating a new one.  Then it started fine.

The docs on pushing a Play 2.0 app to Heroku all disagree with one another too, so I hope I can find a few to post a tutorial based on how I got it working!

Saturday, March 24, 2012

First day with Play

I started looking at play 2.0 for the first time today.  I got a few hours with it at least, and I've been impressed with a few things.

The first and biggest thing is perhaps the most simple: compile on the fly.  Grails does this, but very badly, and if I'm observing right, I think I can see why.  It seems that Play compile checks at request time, not at file save time.  As one who grew up computing, Ctrl-S or it's equivalent has become a nervous tick.  Grails recompiling at save time almost always just ends up trashing the environment as I save about ten times a minute, and I end up having to restart it, which is very slow.

With FSC, Play compiles changes very quickly and I barely notice a lag at all.  It doesn't get stuck anywhere I've noticed yet either like Grails can.

I feel like within a couple of hours, I got pretty far into having a functional, albeit basic web app going.  Working with Anorm is interesting too, I'm not sure if I like how they've done it yet, but after years living with JPA and Hibernate's arcane query structures and unexpected query stupidity (although there was always a good reason, it was still annoying), I find this way of integrating SQL and code better than most.  It has some similarity with O/R Broker which is what I've been using with Jersey so far, but Anorm is more sophisticated and I think easier to work with.

The error reporting in Play is also excellent.  You can see quickly and precisely what went wrong with your code, there's no guesswork and decrypting enigmatic error messages, it just tells you with your source code right there: this is where it's broken!

Friday, March 23, 2012

Scripting in Scala

Today was the first time I've felt comfortable using Scala to write a true script.  Something simple like taking an HTML file, and extracting certain anchor tags which can occur multiple times per line is surprisingly annoying to do in many scripting languages like python or perl.  You often end up with a regex from hell, and I'm not really one for regexes from hell and the declarative style ends up taking far more code that it really should.  You can do this in Perl in a sort of quick way, but it looks pretty damn ugly, and besides, it's 2012, surely we have something that can do this almost as well or better than Perl!

So, with no further ado, I give you my very simple script:

import io._

println(Source.fromFile(new File(args(0))).getLines.filter(_.contains("")).flatMap {x=>x.split("<")}.map {x=>
  (x.indexOf("href=")>0 match {
    case true => x.substring(x.indexOf("href=")).dropWhile("'\"".contains(_)).takeWhile(_!='>')
    case false => ""
})}.filter(x=>{x!="" && x.endsWith(".html\"")}).map {x=>x.dropWhile(_!='"').drop(1).takeWhile(_!='"')}.reduce(_+"\n"+_))

Is this the best way, the easiest or the most elegant, no. It's a script that I needed to write in ten minutes or less.  Almost a throw-away piece of code.

The big thing for me was that I've finally become familiar enough with Scala syntax that I could achieve this is less than ten minutes.  No wandering off to stack overflow to looks something up, or struggling with one of the erasures for the list comprehensions; I could just sit here and type and make it work with minimal debugging fuss.

When I think about the pure horror of trying to do this in Java, I shudder.  If I removed most of the newlines and the imports, this could exists on just two lines (I'm not sure if I can terminate a case clause with a semi-colon or not).  It is probably possible to write this as an immediate script right on the command line, and still be able to read it (well, mostly).

Today is a good day.

Thursday, March 22, 2012

Update on anonymous functions

I am an idiot.  I left out perhaps one of the most fun things about anonymous functions: return data.

I'm still getting used to working in a functional way of thinking, but this is perhaps one of the most fun ways to use an anonymous function.  It might be a little be evil, I'm not sure yet, but it's certainly interesting.  take a simple string concatenation:
function getThingie(x) {
  var a = "I would like to buy";
  var b = "for a good price.";
  var c = "nothing";

  if (x == 1) {
    c = "a dog";
  else if (x == 2) {
    c = "a cat";
  else if (x == 3) {
    c = "a bath";

  return a + " " + c + " " + b;

If we replace this with an anonymous function it can then look like this:
function getThingie(whatThing) {
  return "I would like to buy " + (function(x) {
    if (x == 1) {
      return "a dog";
    else if (x == 2) {
      return "a cat";
    else if (x == 3) {
      return "a bath";
    else {
      return "nothing";
  })(whatThing) + " for a good price.";

I'm not 100% sure which is 'better', but for my money, I find the flow of having the conditional inline as a function more clear. If this were a language like Scala, we could have a match clause here, or a partially applied chain. Ultimately, it puts shit where it goes, and that's my number one rule of programming.  In this case, it means you don't have an assignment somewhere that has a chain of logic that is basically out-of-line of the program flow.  When we read a sentence, we scan along the sentence and piece together information in our head in the order we read it, whether that's left to right or right to left, it's just easier to digest if we don't have to skip around to figure out what is going on in a story, or, in a piece of code.  So, in that way, I think this obeys "put shit where it goes" pretty well.
To give an example, here's one way it might look in Scala:

def getThingie(whatThing) = {
  "I would like to buy " + (x match {
    case 1 => "a dog"
    case 2 => "a cat"
    case 3 => "a bath"
    case _ => "nothing"
  ) + " for a good price"

Arguably this would be an interesting case to use a partially applied function:

def mapMeMyPurhcaseItem : PartialFunction[Int, String] = { 
  case 1 => "a dog"
  case 2 => "a cat"
  case 3 => "a bath"

def getThingie(whatThing) = {
  return "I would like to buy " + 
    (mapMeMyPurchaseItem(x) getOrElse "nothing") + 
    " for a good price.";

Why would you want to do this?  It could be argued that this obeys the "put shit where it goes" rule even better.  The function only returns if the arguments is within the domain of the function, otherwise you must provide an alternative.   It means the fall-through clause is explicit and local so the fall through case isn't hidden inside a function.  Partially applied function are extremely powerful constructs I'm beginning to learn, and I think I'm going to find them to be a good friend in building extremely robust programs, but that's a story for another time!

Tuesday, March 6, 2012

Programmers, guns and analogies

An analogy I've heard bandied around over the years, not just by the Ruby folks, is the programmers and guns analogy.  Give people freedom and they won't destroy the world, they'll be happy.  Give a bunch of programmers the proverbial AK47 and they'll not start shooting each other.

For all the ways this is a bad analogy, and a bad model, none is worse than the fact that it's basis it completely flawed.

Bad code is not something you have to pull the trigger on, it's the default.  It's like bad art, or bad bricklaying.  When you don't know any different, you make bad art, lay crooked bricks and write crappy code.  People don't get born into a state of understanding and skill.  To extend this analogy thing, the gun is already firing, and you have to work to dodge it.  Giving programmers the proverbial gun isn't giving them a tool.  It's like a gun that once you've pulled the trigger, it won't stop firing, you just better hope you figure out how to aim it so it doesn't hit anyone else.  Friendly fire in a war zone is a leading cause of death.  Only extreme training will reduce it, and it's rarely eliminated.

Of course, it's coding so there aren't lives at risk right?  Well, unless you're writing the software that flies a 747 through the sky, or a system that measured medication for the pilot who's flying the 747, or perhaps the code that set his smartphone alarm off two hours early and now he's low on sleep when the emergency happens.  It might feel like an edge case, until you consider all the possible ways the human part of that system, or it's dependent systems, like the flight crew, the ground staff, the air traffic controllers might have been affected by a simple code bug which could end up being just as serious as a malfunction in the guidance system of a 747.

Hyperbole?  A little, but also, not entirely.

Saturday, March 3, 2012

Scala : On constructors and companion objects

With companion objects, you can utilize the apply method to generate constructors that look like case classes.  This might not seem like much, but it's a nicety that feels idiomatic to me at this point.  If you're new to Scala, this is something that I think is worth a moment of your time.  It is helpful not only in taking about constructors and companion objects, but most importantly the apply method.  The apply method isn't something I really had a feel for until quite recently, and it's such a powerful mechanism that I think it really should be Scala 101.  It's a difficult concept to work with when you're still very much in the Java mindset.  I think there are aspects of Scala like this that fit in the mind of a C++ programmer more easily than a Java programmer.  Let's have a look at some code.

import io.Source

class Thingy(name: String, info: String, saveFile: File) {
  val fw = new FileWriter(saveFile)

  def this(name: String, info: String) = this(name, info, "data/"+name.filter(Character.isLetter(_)))

object Thingy {
  def apply(name: String, info: String) = new Thingy(name, info)
  def apply(name: String, info: String, File: saveFile) = new Thingy(name, info, saveFile)
  def apply(name: String) = {
    val file = new File("data/"+name.filter(Character.isLetter(_)))
    new Thingy(name, Source.fromFile(file).mkString, file)

The Thingy class is used to represent a simple data object that correlates to a file.  This code isn't DRY and it could stand some improvements, but it's a simple example that works for the purposes of a demonstration.

There are two things here that both kind of look like Java classes.  One is labelled with the object keyword and the other with the class keyword.  In simple terms, the object is like an class definition that contains the methods that would have been declared static in a Java object.  It's a bit more than this, but I'm not gonna delve into that here.  The one that is labelled with the class keyword is more like a typical Java object.  It has instances and maintains state (sort of).  The definition that is labelled "object" is called a companion object in Scala.

Initially many Java programmers, myself included, look at this and ask why the heck would you want to do that?  Seems a bit clunky perhaps.  Then you come across the apply method.  This one use case for me, helped give the object type a specific useful meaning beyond just static methods.

The apply method is a special marker in Scala.  Let's look at a simple case, a List:

scala> val k = List("one","two","three")
k: List[java.lang.String] = List(one, two, three)

scala> k(2)
res1: java.lang.String = three

This uses the scala REPL which can be accesses just by typing "scala" (assuming you have the scala executable in your path).

The call k(2) is just like k[2] in Java.  In this case we can see that it's just like an array index operator.  The trick is that it's actually calling the apply() method on the class (not the object here, but the usage is similar).  The interesting thing is this means for a custom object, like our Thingy, we can define what behavior we want when we call an object in this fashion.  In our case, we have three apply methods.  Two that create an instance, and one that acts a bit like an array index.

Now when we call Thingy("file_I_want_to_read.txt") I get back a Thingy that has been fully initialized from the file just like I might call something like
new Thingy(new File("data/"+name.filter(Character.isLetter(_))).

In Java, we cannot execute any code in a constructor prior to calling the super() method.  This is pretty annoying at times, and we end up making work-arounds for this by using the factory pattern.  The factory pattern is just fine, but I feel like it's overkill for something this simple, and Scala has a handy way of doing this that is pretty similar to the factory pattern, but syntactically much nicer*.

The object gives us the power to do stuff before we perform the initialization of our object, and therefore makes this very easy.

You may have noticed that the "new" keyword went away in there.  Using the apply method on the companion object, we have created what more or less appears to be what a static constructor might look like in Java, or like I mentioned, a short-cut for a Factory.  It might be more convenience than anything, but it makes our code look better, removing the ugly details of constructor somersaults from the object itself and removing the littering of "new" calls throughout our code.  Because it's a separate method call, it is not limited to returning an object of the same type as it's namesake.  This has interesting implications/applications for dependency injection and cache management.

* It it easy to dismiss much of the niceties of things like Scala and Groovy as "syntactic sugar", and whilst that's true in some cases (not so much in others), sugar can sure make my coffee taste a whole lot better.  Syntactic short-cuts like this can make your code both more readable and less bug prone, so give it a go before you dismiss features as "syntactic sugar".