James Carr | Rants and Musings of an Agile Developer

Archive for May 2010

This morning I started my day off with another problem to learn scala better with and I wanted to only devote 30 minutes max to it as we had a busy day ahead. With this in mind, I did a simple factorial kata that I’ve done multiple times before in other languages to practice recursion. So I started off with the first spec:

import org.specs._

class FactorialSpec extends Specification{
  "factorial" should {
    "return 1 for n = 1" in {
      Factorial(1) must be equalTo(1)
    }
  }
}

Of which I just returned n. I then wrote the next example which passed out of the box and finally wrote two more examples I knew would make me solve the problem.

class FactorialSpec extends Specification{
  "factorial" should {
    "return 1 for n = 1" in {
      Factorial(1) must be equalTo(1)
    }
    "return 2 for n = 2" in {
      Factorial(2) must be equalTo(2*1)
    }
    "return 6 for n = 3" in {
      Factorial(3) must be equalTo(3*2*1)
    }
    "return 6*5*4*3*2*1 for n = 6" in {
      Factorial(6) must be equalTo(6*5*4*3*2*1)
    }
  }
}

The first surprise I had was that scala apparently doesn’t have any ternary operator so I tried the following solution:

object Factorial extends (Int => Int){
  override def apply(n:Int) =  {
    n * (if(n > 1) apply(n-1) else n)
  }
}

This was fine and all, bit I decided to read around a bit more and see what features in scala I could apply to change this. FoldRight and foldLeft appeared to be right up my ally:

object Factorial extends (Int => Int){
  override def apply(n:Int) = (1 to n).foldRight(1)(_*_)
}

foldRight works like this… it takes each element moving to the right for each one and, starting with the base number (in this case 1) multiples it to a running result (indicated by the second _). So for 4 this looks something like this:

1*1 = 1
2*1 = 2
3*2 = 6
4*6 = 24

Very interesting. There’s also a shorthand notation for foldLeft and foldRight, but so far I have decided against using it as it makes it look like code only some mathematical genius could understand. ;)

EDIT: Okay, looks like I had it wrong. foldRight starts from the tail of the collection and works its way back while foldLeft starts from the head of the collection and works its way to the end.

No tags

May/10

28

Friday Scala Kata

As part of my quest to learn and understand scala better I’ve committed myself to doing a weekly kata and thought it’d be fun to spin it as kata I could share the problem each friday with a follow up of a solution the following week (and even better, allow others to participate too).

I began this morning by searching the the Project Euler site for interesting problems and decided that Identifying Traingle Words would be a good kata to start with. :)

The kata sounds simple… convert each character in a word to it’s corresponding number value (e.g. 3 for c, 5 for e, etc), sum them together and the word is considered to be a Triangle Word if the sum is equal to a number in the sequence of triangle numbers.

Good luck! Feel free to post solutions here (but try to link to http://gist.github.com for code samples as my blog comments don’t current format code samples).

No tags

May/10

26

Finding Good Problems for Code Katas

Today one of our “product owners” (or at least close to that role within the organizational structure) overheard me discussing my recent code kata with someone and he linked me to an interesting site full of all kinds of mathematical problems to solve: http://projecteuler.net/.

Now if I ever find myself wanting to do a code kata and have no idea where to stat I can just take a gander at their problems page. :)

No tags

May/10

26

Follow up on the Scala Prime Factors Kata

So my fellow OCIer Tim Dalton took up my challenge to find me the “scala way” of implementing the solution in a nice one liner. I changed the example in the spec to allow a result of a list with 1 in it instead of an empty list to get rid of the conditional… the result was tasty. :)

Also goes to show there’s still a lot more for me to learn about scala.

(for (i <- Stream.range(2,n/2); if n % i == 0 ) yield (i)).headOption.map{x => x :: apply(n / x)}.getOrElse(List(n))

He also quickly followed this up with a 2.8 compatible version as well:

object GeneratePrimeFactors extends (Int => List[Int]) {
                override def apply(n:Int) = (for (i <- Stream.range(2,n/2); if n % i == 0 ) yield (i)).headOption.map{x => x :: apply(n / x)}.getOrElse(List(n))
}

No tags

May/10

24

Scala Prime Factors Kata

So recently I started committing myself to understanding scala better and a perfect way of doing this is to start practicing different code katas in the language. So early this morning I started the day by doing the Prime Factors Kata in scala using specs to drive development and sbt to build run tests. The thing I really like about sbt is you can run ~test and just like ZenTest file changes triggers all the specs in the project to be re-ran.

Overall my solution was pretty simplistic and comes from a java developer’s understanding of scala. I spent 30 minutes on it and shared the result on github under scala-prime-factors. Feel free to criticize to your heart’s desire and let me know of better ways of solving this… I keep feeling like there must be a simple scala one liner that I just don’t know about. ;)

For those who are lazy, here is the spec:

import org.specs._

class primeFactorsSpec extends Specification {
  "should generate empty list for 1" in {
    primeFactors.generate(1) must be equalTo(List[Int]())
  }
  "should generate a list with 2 in it for 2" in {
    primeFactors.generate(2) must be equalTo(List[Int](2))
  }
  "should generate list with 3 in it for 3" in {
        primeFactors.generate(3) must be equalTo(List[Int](3))
  }
  "should generate a list with 2 and 2 in it for 4" in {
    primeFactors.generate(4) must be equalTo(List[Int](2,2))
  }
  "should generate a list with 2 and 3 in it for 6" in {
    primeFactors.generate(6) must be equalTo(List[Int](2,3))
  }

  "should generate list with three 2s for 8" in {
    primeFactors.generate(8) must be equalTo(List[Int](2,2,2))
  }
  "should generate list with two 3s for 9" in {
    primeFactors.generate(9) must be equalTo(List[Int](3,3))
  }
}

And here is the terrible looking solution:

object primeFactors{
  def generate(n:Int) = {
    var x = n
    var factors = List[Int]()
      for(i <- 2 to n)
        while(x % i == 0 && x/i > 1){
          factors += i; x/=i
        }
    if(x > 1)
     factors += x
  factors
  }
}

No tags

May/10

23

NFJS Day 3: Test Doubles With Mockito

Bright and early I got started with my own presentation today and i thought that I’d retrospect on it a bit and identify areas to improve upon.

For the most part I felt the introduction to Test Doubles and what they are flowed well, however I did speak very very quickly. In the future I’m going to try to slow down a bit (although I did get no complaints about this except from my “wife-to-be” Than).

I did some live code samples of practically every single Mockito feature and felt that this went real well (and was happy to see some “ah ha” faces in the audience over some features) but it also seemed like the live code samples were a minefield of danger waiting to happen (and there were a couple times I kind of forgot what I was going to demo next, although I kept this hidden by talking more about the previous feature).

I’ll be giving the presentation again in Des Moines on the first, so I’m going to make the following improvements going forward:

  • include empty test methods from the start that I can just fill in
  • Re-arrange the content a bit for better flow
  • reduce slide content during the live coding session. I talked about what was on these slides while coding, so the slides just added noise that often times got skipped
  • Slow the pace down a bit

Overall I was quite happy at how it turned out and glad that it ran for the full 90 minutes without any rehearsal. Thanks to all who turned in your feedback forms and if you attended the talk and didn’t, please leave me some feedback here! :)

No tags

The second session of the day that I attended after completing my Mockito talk was World Class Builds with Gradle. I debated going as I already use gradle and even gave Michael a bit of advertisement by showing some of the early attendees to my session my gradle build file, however I decided to go… I might learn something new and I could give a fellow OCIer some feedback on his talk. :)

One aspect I liked of his presentation was he really started by breaking down how tasks work in gradle and the basic building blocks of how they work in the scope of the build file. for the most part, I felt this flowed pretty smoothly with the gradle user guide.

At first I didn’t think show the example of using ant style build in gradle was really a good idea… when I saw it, I thought that this is really just as verbose as ant but just written in groovy instead of xml. But what was good about showing a gradle build using almost nothing but ant tasks was how one could migrate from ant to gradle in the interim and just use the same ant tasks until they “gradlefy it”. And when he did show how easy it is to set a build up with gradle, it was a breath of fresh air. :)

Overall I felt like it gave a good overview of gradle and how to use it not just for building java apps, but he also gave a good real example of how you might migrate from something like ant to gradle.

No tags

I put together a quick 5 minute presentation yesterday for the NFJS 300 sessions and thought I’d share it online. I was pretty impressed how it turned out giving that I only spent 10 minutes putting it together and only thought of it half an hour before the 300 sessions. ;)

The main point I made was that if you want to succeed with agile (or at least do pretty good with it) I’d suggest using no tools as part of your adoption. Most companies scurry to some digital tool that only helps impede communication rather than aid communication. Even though some of the tools might be good and work well (I’ve used a few of them) I think they should be avoided in the early stages so that people can get used to the concept of “card as a placeholder for a conversation” and understand how to use a burn down and burn up chart versus having it generated for them.

I then just closed out the talk by stressing the importance of collaboration and team work. Pretty simple, but I hope effective. ;)

No tags

Looking to expand my scala skills, for the second sessions I decided to attend Michael Nygard’s session on Internal and External DSLs in scala. What I really liked was right off the bat how he illustrated a very simple example of internal DSLs in scala for those new to scala and DSLs:

def isComment(s : String) = s.startsWith("#")

which could also be done with no puncutation

def isComment(s : String) = s startsWith "#"

But that was just the simplistic starting point. The real world example that he spent a good chunk of the session tearing apart looked like this:

apache offers "HTTP" on 80
apache offers "HTTPS" on 443

apache contains "mod_cm" needing "CMLDRP"

The above is actually real scala code that can be compiled and ran by scala! The trick is a nifty combination of factory methods, implicit functions, and scala’s ability to have punctuation optional. Combining all of these plus more together yielded a nice, higher level DSL like the one above. He then showed the dsl being used within specs as an example.

Moving on, external DSLs were covered and how to create a grammar parser using the building blocks that scala provides and how to use trait parsers to aid in parsing a grammar. Combinators played a big part in tall of this and creating a tree of combinators. leading from this in depth explaination, he showed how to use Parsers.Parser for parsing the structure.

I really enjoyed the session… I even got some of the examples he showed using combinators working on my laptop. There’s definitely a lot of new scala knowledge for me to digest! :)

No tags

May/10

22

NFJS Day 2: iBeans

This morning I was very torn about what sessions to go to… Spring 3, Scala Programming, iBeans and Practical Agile Database Development were sessions I had to choose from (I had already seen the session Neal Ford was giving, or something like it). With my recent work and JNB article on Camel, thought I’d give iBeans an investigation.

For the most part, ibeans is pretty much similar with camel with the concepts of channels, destinations, messages, etc… it’s kind of a micro esb. What I liked most was the iBeans for commonly used social media services like twitter, flickr, etc. There were tons of good examples of how to use iBeans within your application to work with multiple services… however I wish there would have been some hands on examples. :(

Of course, this is to be expected unless the session is explicitly a hands-on workshop, so that wasn’t too big of a deal. The examples provided were quite enough to get me interested and download the core pieces to get started. You can also find lots of community contributions on github.

Like with camel, I think what interests me most is the possibility of connecting channels to a comet based endpoint to send and receive messages to the client side of a web app. Must investigate further. :)

No tags

Older posts >>

Theme Design by devolux.nh2.me