Author Archive

Ist der mobile Markt noch nicht bereit für Lean Startup in Reinform?

Gestern habe ich ein Interview mit Frank Thielen mit dem reißerischen Titel “Das Lean Startup ist tot” gelesen. Beim Lesen musste ich einige Male den Kopf schütteln und ich möchte hier kurz zu einigen Aussagen meinen Standpunkt beschreiben. Ich empfehle ausdrücklich das Interview selbst zu lesen, um den Kontext für die folgenden Zitate und meine Antworten herzustellen.

Das komplette Interview basiert auf der Annahme, dass “App Stores [...] zum dominierenden Distributionskanal für Inhalte und Services” werden. Ich habe auch eine Annahme, nämlich, dass App Stores über kurz oder lang von Web-Apps verdrängt werden, und zwar ironischer Weise genau aus den Gründen, die im Folgenden als Argument für den Tod von Lean Startup angeführt werden. Ich gehe davon aus, dass dies analog zu Desktop-Anwendungen passiert, die es heute nur noch für wenige Anwendungen gibt. Aber sei’s drum, gehen wir mal davon aus die erste Annahme stimmt und wir müssen unbedingt für App Stores entwickeln.

Im Interview wird behauptet: “Eine App wird also mindestens einen Monat lang draußen bleiben, ohne dass ihre Macher etwas nachbessern können.” Die Verzögerung liegt daran, dass Apps durch den App Store Betreiber erst geprüft und anschließend freigegeben werden muss. Mir als Entwickler ist das ein Dorn im Auge, weil es agile Softwareentwicklung im Allgemeinen und nicht nur Lean Startup Techniken behindert. Davon abgesehen ist die Aussage falsch. Meine eigene Erfahrung (und die meiner Kollegen bei it-agile) ist, dass es wenige Stunden/Tage dauert bis ein Update einer App im Store erscheint, nachdem man sie hochgeladen hat. Speziell bei Fehlerbehebungen kann dies in der Regel relativ schnell geschehen.

Als nächstes wird behauptet, “Ein Startup, dessen App eine Reihe negativer Bewertungen erhalten hat, kann daran viele Monate lang leiden. Denn neue Angebote müssen vom Start weg den hohen Ansprüchen der Nutzer gerecht werden. Jedes Release muss sitzen, damit Apps sich keine Ein-Sterne-Bewertungen einfangen.” Hier verbirgt sich eine weitere implizite Annahme, nämlich, dass ich sowohl das zu lösende Problem, als auch die passende Lösung dazu schon in Gänze verstanden habe. Genau das ist aber Teil von Lean Startup. Ich gebe zu, das Verstehen von Problem und Lösung (Problem/Solution Fit) werde ich in der Regel nicht in einem App Store, sondern mit Interviews validieren. Aber auch Features in meinem Produkt möchte ich zunächst nicht perfektionieren, bevor ich nicht verifiziert habe, dass genügend Anwender dieses Feature für nützlich halten. Natürlich möchte ich vermeiden, meinen Anwendern (auch den Early Adopters) Abstürze zuzumuten, aber ich glaube nicht, dass die UI und Design beim ersten Wurf perfekt sein muss. Bewertungen neuerer Versionen werden zudem stärker gewichtet und lassen alte Bewertungen verblassen. Davon abgesehen ist es ja ein offenes Geheimnis, dass Bewertungen in App Stores zu großen Teilen manipuliert sind. Aber das ist ein Thema für einen anderen Blogpost.

“Mindestens für drei mobile Plattformen sollte man entwickeln und sich dafür nicht zu viel Zeit lassen.” Wie auch im Interview erwähnt wird, gilt dies vorwiegend für Apps, die ihren Schwerpunkt auf Interaktionen zwischen Benutzern haben. Selbst da sehe ich es aber als Skalierungsproblem und keineswegs die Notwendigkeit sofort auf allen Plattformen verfügbar zu sein.

“Große Player” beherrschen den Markt, daher kann man “im B2C-Segment aktuell ohne große Mengen an Venturekapital nicht überleben” ist eine weitere Aussage, die ich nicht so stehen lassen kann. Mit den “großen Playern” direkt zu konkurrieren ist selbstverständlich schwierig und teuer, daher wird man versuchen, den Markt zu segmentieren und eine Nische zu besetzen oder aber einen neuen, bisher nicht existierenden Markt zu erzeugen.

“Die meisten Nischen sind ja nunmal bereits von den großen Firmen besetzt, und wenn nicht, dann geschieht dies bald.” Wir haben also schon alle möglichen Apps gebaut? Ab jetzt kommen nur noch Wiederholungen? Keine weitere Innovation mehr möglich? Das wäre schade, ist aber zum Glück äußerst unwahrscheinlich.

“Aufgrund der Komplexität mussten wir sehr viele Funktionen einbauen. Ein Lean-Startup-Ansatz kam schon deshalb für uns nicht in Frage.” Mir ist bewusst, dass es schwierig ist komplexe Probleme kleiner zu schneiden. Für mich aber meist ein Indiz dafür, dass man sich vorher noch nicht genügend mit dem Verstehen der Probleme und der möglichen Lösungen auseinander gesetzt hat. Was ist das Hauptproblem, dass ich versuche zu lösen? Meist ist dies doch mit einem kleineren MVP zu überprüfen, als man denkt.

“Ich denke, das Erfolgsrezept ist, ein Problem zu lösen, das man selber identifiziert hat, dies mit dem Streben nach Perfektion und der Liebe zum Detail umzusetzen und es dann vom Tag eins international anzubieten.” Mit Leidenschaft hinter seiner Idee und seinem Produkt zu stehen, ist selbstverständlich nur empfehlenswert. Aber bewusst auf Feedbackschleifen zu verzichten und stattdessen sein Produkt zu perfektionieren, halte ich für die meisten Anwendungen für äußerst schädlich.

Im Großen und Ganzen, glaube ich, Lean Startup ist wohlauf, und blickt einer blendenden Zukunft entgegen.

Vielen Dank an Holger Bohlmann, Fabian Dittberner, Florian Eisenberg und Doreen Timm für ihren wertvollen Input.
Image by Eric Johansson

The best technology stack for web startups

Throne of JS[This is my personal opinion based on my experience. Your mileage my vary.]

Rails rulez…

The typical technology stack for web app startups these days seems to be Rails* with Javascript (jQuery, CoffeeScript) on the client. It’s battle proven and really great for rapid prototyping to get that early customer feedback before wasting too much time and money on building the wrong thing.

What bothers me is that my Rails apps always turn out to be really JavaScript-heavy. As the project grows the Javascript part gets more complicated really quickly. But even worse than that, there’s a mental disconnect between working with model objects in Ruby in the backend and manipulating the DOM with Javascript in the frontend.

For handling the complexity you might lean on batman.js or ember.js or something similar. They also come with some sort of data-binding which eases the burden of DOM manipulation. But you still need to write code in Ruby on the server and JavaScript on the client. In my experience, you sooner or later end up duplicating some of your functionality.

… but JavaScript is on the rise

If you want to use only one language on the server and the client you are stuck with JavaScript for now (and the foreseeable future). Now, enough has been said about the drawbacks of JavaScript as a language. I mostly agree. That’s why I like to use CoffeeScript, which makes it a whole lot more enjoyable.

What is great about Rails though is the whole scaffolding and “convention over configuration” thing, which allows for quick bootstrapping of new applications. There are some up and coming frameworks to fill that gap in the JavaScript ecosystem. Most notably derby.js and meteor.js. I personally am a big fan of meteor, because of it’s reactivity model and latency compensation. It’s not quite ready for prime time though. But definitely worth keeping an eye on.

In a recent conference called ‘Throne of JS‘ the creators of the most popular JavaScript libraries and frameworks came together and compared notes. I can recommend reading Steven Sanderson’s write up (creator of Knockout) to get an overview on what’s hot in JS-land. Over the next few weeks videos of the Throne of JS talks will pop up at InfoQ.

*Please direct all your hate mail to djangonauts@qualityswdev.com where it will be politely ignored.

The 7 most influential people on Lean Startup

[Warning: This post includes a few tongue in cheek remarks. No offence intended. If smack talk is not yours, stop right here. You've been warned.]

This is a list of the most influential people on Lean Startup*. The criterium to get on the list is to influence me in my thinking about Lean Startup. I know that’s a pretty small sample size, but it’s my list, so suck it.

Ash MauryaAsh Maurya (@ashmaurya): Ash wrote the book Running Lean: Iterate from Plan A to a Plan That Works. It’s the best book on Lean Startup I have come across so far. This is the first time someone describes a step by step repeatable, actionable process for building products (I am looking at you Eric) in few understandable words (unlike other books written by professors for professors). Right now he’s running a company called Spark59 with the goal to help entrepreneurs succeed. As you read this they are slaving away on building a new metric tool that gives you actionable metrics instead of just numbers. It looks pretty promising. I bet the guys over at KissMetrics are shitting there pants right now.

 

Eric RiesEric Ries (@ericries): I first heard about Eric when he was still working at IMVU and was making Continuous Deployment popular as part of something he called lean startup. He came up with the term as an application of Lean Thinking. At some point he turned his very successful blog Startup Lessons Learned into the well known bestseller The Lean Startup, which brought his ideas to the masses and took the lean startup movement to a new level.

 

Steve BlankSteve Blank (@sgblank): Steve’s claim to fame is a process called Customer Development described in his book The Four Steps to the Epiphany, which predates and heavily influenced the lean startup method. He was a serial entrepreneur and early advisor of Eric Ries. He is now teaching students at Stanford (and other places and online) about entrepreneurship with his Lean Launchpad class. This class gave birth to another book called The Startup Owner’s Manual, which is pretty heavy reading though.

 

Dave McClureDave McClure (@davemcclure): Dave came up with Startup Metrics for Pirates: AARRR!, which is his take on user life cycle funnels. He’s the founder of a seed fund & incubator program called 500 Startups. This guy has worked at a whole lot of well known startups and has invested in even more so. He knows the startup scene like no one else, plus he is a very likable guy. You should watch his interview with Startup Grind.

 

Alex OsterwalderAlex Osterwalder (@alexosterwalder): Alex is renowned for the Business Model Canvas, which is the basis of his book Business Model Generation. The gist is: Don’t waste your time writing a lengthy formal business plan that no-one is going to read anyway, but instead describe your business model on a nine-box-canvas, which you keep iteratively refining as you try to (in-)validate your assumptions. I personally prefer Ash’s modified version of it, which he calls Lean Canvas.

 

Dharmesh ShahDharmesh Shah (@dharmesh): Dharmesh coined the term Inbound Marketing, which is also the name of his book and the basis for his company HubSpot. In essence, inbound marketing is about getting found by customers, rather than spamming the whole world with ads and hoping for a few clicks that actually convert to sales (aka spray-and-pray). You can find all sorts of free marketing resources on their website. I recommend you check it out.

 

Kent BeckKent Beck (@kentbeck): I shouldn’t have to explain this. Kent is just generally awesome and has to be on every best-of list related to software development. As with everything else in the agile and lean space lean startup is really just XP in different words.

 

I kinda feel like there is someone missing in this list from the design and UX corner. Maybe that is because design is one of my weak spots or maybe because designers are not as loud. If there is anyone else you think should be on the list, please let me know in the comments.

* The Lean Startup is a trademark** and service mark owned by Eric Ries
** I am sure this pays of for you Eric, but writing this on every page I use the term ‘Lean Startup’ is a major pain in the ass!

Willing spontaneous pairing

jam sessionOne of the most debated and debatable XP practices is Pair Programming. Here is what I found to work best for me: willing spontaneous pairing (to carry on Arlo Belshee‘s wonderfully ambiguous ‘Promiscuous Pairing‘).
This means I don’t pair all the time. Mostly because
  • my working hours don’t line up exactly with those of my team mates. I am an early riser. That means in the morning I am usually already in the middle of something when my colleagues come in and I consequently leave before they do in the evening.
  • when I am working on a task that seems obvious to me, I feel too driven, when someone is sitting next to me and I end up making bad choices in a hurry. This happens when typing is actually the limiting factor and I am feeling like I am wasting my pair partner’s time.

But I am still very willing to pair in general and I do appreciate the advantages of it.

will·ing /ˈwiliNG/

Adjective:

  1. Ready, eager, or prepared to do something.
  2. Given or done readily: “willing obedience”.

That means whenever I feel like I could use a second opinion on something like a design decision, I will readily ask one of my team mates to pair with me. And on the other hand when one of them is asking me to pair with him or her I am eager to do so.

I try to let the pairing happen spontaneously, i.e. before getting stuck with a problem.

spon·ta·ne·ous /spänˈtānēəs/

Adjective:

  1. Performed or occurring without premeditation or external stimulus: “spontaneous applause”.
  2. (of a person) Having a natural, and uninhibited manner.

I try to avoid spending too much time pondering a hard problem on my own. Be it a difficult design decision or a gnarly bug I just can’t figure out how to fix. When I do ask one of my colleagues to help me with something, I ask them to finish whatever they are working on right that moment or at least get to a point, where they can pick it up easily again after they paired with me. With this, I hope to minimize the interrupting nature of my request.

These pairing sessions can last anything from minutes to days. Sometimes I just need my pair partner to be my rubber duck and I already get to the solution while I am explaining what I did so far to get to where I am and go ahead implement it on my own. Other times it might take longer to figure it out and we decide to implement it together.

Before asking someone to pair with me, I mentally structure the explanation part of getting them up to speed with what I am working on at the moment and the problem I am facing. Many times I end up doing some refactoring during that process.

I do believe that pairing actually leads to different and most likely better solutions than programming on your own. My assumption is that by practicing willing spontaneous pairing I still get some, if not most of this benefit.

With this approach I am hoping to mitigate the downsides of pairing while still reaping its benefits. Like everything else pairing is a trade-off and I don’t think it’s helpful to be dogmatic about it.

Metrics are useless on day one of a startup

measureIn the it-agile Startup March we tried to make decisions based solely on hard facts. No more guessing or subjective opinions, just objective numbers. This appealed a lot to the mathematician in me. I, and most other participants, had just read Eric Ries’ book The Lean Startup. We wanted to use his process of Innovation Accounting to make decisions based on validated learning derived from metrics, i.e. automatically measured customer behavior. Hello, wonderful new world of objective decision making!

Context: We tried to solve the problem of online (distributed, asynchronous) discussions that don’t come to decisions.

Unfortunately, here is what really happened. As far as I can tell, we made four major mistakes:

  • First and foremost, we tried to use metrics too early on. Metrics are absolutely useless before you can drive (a statistically relevant) amount of users to your site. What we retreated to after a while, and what we should have done in the first place, is to talk to potential customers. Steve Blank distinguishes the two steps Customer Discovery and Customer Validation in his Customer Development Model. We tried to skip ahead to step two where you test your “ability to scale against a larger number of customers with another round of tests, that are larger in scale and more rigorous and quantitative”. Here metrics make sense. In contrast, he suggests to get out of the building and talk to customers in step one.
  • We didn’t define specific success / failure criteria for our experiments. Because we didn’t articulate our expectations for our experiments, we always ended up having a hard time trying to interpret the results and still making subjective decisions after all. Starting an experiment without specific success / failure criteria is usually a waste of time. All experiments we started this way ended up in the ‘indecisive column’ on our board.
  • We expected metrics to tell us what to do. In a best case scenario metrics will tell you if something is working or not. That is, if you defined specific success / failure criteria before the experiment as described above. But metrics can’t tell you why something did or didn’t work or how to fix it in case of the later.
  • We didn’t understand how the data was collected. There is several great tools out there that can help you collect usage data of your site and condense them into actionable metrics. The problem is, if you don’t fully understand what exactly is measured, the measurement is not very trust-worthy. Especially, if you are trying to compare numbers from several tools. For example, a ‘unique visitor’ is defined differently by almost every tool I know. I suggest to measure the few metrics you need yourself. Only then can (/ should) you be sure to fully understand them. Usually this can be done by a few simple DB queries.

To be fair, all of the above mistakes are described in Eric’s book. It’s just that sometimes you have to make the mistake yourself to fully comprehend its consequences. So go ahead and see for yourself (if you must).

Further reading:

Photo by Chandra Marsono

The it-agile Startup March: Lessons learned

bart_simpson_chalkboardThis last month six colleagues and I carried out a little experiment: the ‘Startup March‘. We decided that instead of doing development, training, and consulting for our customers, we would dedicate all of our time to work on an idea for a startup. We wanted to put the ‘Lean Startup’  method, as made popular by Eric Ries’ book, to the test. Here’s a list of learnings we came up with and my personal interpretation of them:

  • Co-location: Communication gets orders of magnitude more difficult when a team is distributed. In the early days of a startup there is plenty to talk and to argue about. Not being in the same room will inevitably slow you down. We also found it helpful to be somewhere else than our normal offices, away from all the distractions that would pull us back to the day-to-day duties for our customers.
  • In the beginning focus on individual users: We tried to make informed decisions about our product, depending on statistics, from day one. This is hard, when all of your data is statistically irrelevant. So, we decided to interview people and focus on our early adopters and their needs first.
  • Know your metrics tool(s): Your metrics about your fancy experiments will be useless, if you don’t know what they mean. What is a unique visitor? Someone coming back during the same session? Someone on the same device? Are you counting yourself? If you don’t know this, don’t bother measuring it.
  • Don’t neglect growth: It’s usually more fun to spend time on working on features that create more, but you also need to constantly think about how to get more people to use your tool. In order to do this, you should understand as precisely as possible who your customers are and which problem you are solving for them.
  • A moderator can be helpful: We made all the decisions along the way in the team without having an authority like a Product Owner. In the end we concluded, however, that a moderator like the Scrum Master role would have been helpful during some discussions. This doesn’t have to be the same person all the time, but it might be helpful to have this dedicated role to keep discussions from dragging on longer than they have to.
  • Sync often: Most of the work was done in groups or pairs. To get everyone up to date, we did brief stand-up meetings throughout the day. Usually between two and four of them. With most of the system changing all the time it is important to keep everyone pulling in the same direction.
  • Release more often and know when to clean up: In a startup environment you are optimizing for customer feedback. This is very different to a project that has been going for a couple of years. Clean code is important in the later, not so much in the former. I am not telling you to intentionally write bad code, but to make a conscious decision about the time you invest in cleaning it up. The half life of code in a startup is very short. There is no point in writing the cleanest code you can for an experiment you are going to throw away tomorrow. When some functionality has stuck around long enough and is actually valuable to your users, and you keep breaking it unintentionally, it’s probably time to write some tests and start refactoring it.
  • Explain your features to your users: It may seem obvious to you why and how to use your tool, but it’s not obvious to your users. So, explain features and what value they will provide.
  • Present to an independent audience about your idea early on: We presented our idea and our first findings about Lean Startup after three weeks to an independent audience at an evening event. This forced us to review our results thus far and we received valuable feedback by the participants.
  • Don’t force a process on yourself: If you’ve got a team of experienced people, don’t force yourself to use a specific process. Scrum by the book is intended as a starting point for teams that are stuck. A team that has understood agile values will figure out it’s own process.
  • Decide on the general topic and the techno stack and get to know them ahead of time: If you are planning on doing a similar experiment, where you spend a limited amount of time with some colleagues to work on a startup idea, do yourself a favor and get to know the problem domain and the technology ahead of time. This way you can jump right in on day one. Otherwise, chores like setting up your dev machine and working through a tutorial, will eat up your precious time. BTW, we went with Rails, which was great to get off the ground quickly.
  • Get a designer on the team: Most developers know how to make a piece of software work, very few of them also know how to make it look good. No-one will use your tool if it looks like it was developed in the ’90s.
  • Have a team event early on: It will help your team gel quicker. The work will be more effective and more fun.
  • Team size: There was no agreement on this amongst the team, but I have an assumption that a smaller team would have been more effective. I base this assumption on another assumption that a smaller team would have needed less time for communication, both synchronizing and debating. Others argue that, if we took the four team members with the most oposite opinions it would have taken us just as long to debate and if we took the four team members with the most aligned ideas we would have had less inovation. I still think in the early days of a startup, as long as you got all the necessary skills on the team, a smaller team will outperform a bigger team, because of the frictional losses for synchronizing about all the moving parts.

All in all, for me the focus on experiments to prove one’s assumptions is the most important contribution of Lean Startup to my personal tool box.

Further reading:

Lean startup language design

Dart

At a recent hackathon I was noodling around with Dart. I thought, it was great that Google made it particularly easy to start playing with their new language by putting an interactive shell – the Dartboard – on its home page. No download, no installation, instant coding. Very nice. On the other hand they made it unnecessarily hard to find any information about the language on the internet by calling it Dart. Particularly when you search about throwing exceptions…

Trying to implement a small project in this new language I haven’t seen before made me wonder: How effective do language designers use feedback? On Dart’s website they ask for feedback, which is mostly organized in groups. What they should really do is to bring in some developers and monitor them as they try to solve simple tasks with the language under development. After all, creating a language is just another software project with end users. Or better still, at this stage they should  log and analyse compiler errors from the shell on the website. If people keep producing the same compiler error over and over it is probably an indicator that this particular construct of your hip new language just might not be very intuitive.

Let’s assume Google logged and analysed what happened in our session from this week’s hackathon – and they most likely did, they would come to the conclusion that having two different notations for creating a function was confusing for us. Especially, because only one of them caters for certain scenarios. Either that, or that there were two idiots in front of the computer who needed 20 minutes to figure it out. You can judge for yourself:

main() {
  (function() => print('Hello again'))();
}

This works just fine. It creates a function that prints ‘Hello again’ and executes it.

main() {
  (function() => throw new Exception())();
}

This on the other hand gives you a (not very useful) compile time error that the token ‘throw’ and ‘new’ are not expected. While this is entirely true, it sent us in the wrong direction to check how to throw exceptions. While the actual mistake was that you can only use expressions with the => notation. If you want to use statements, like throwing an exception, you need to omit the arrow and use a block with curly braces instead.

main() {
  (function() {throw new Exception();})();
}

I hope other language designers will follow Google’s example and show off their language as early as possible to get feedback on their decisions. Maybe even without the developers being aware of it. I don’t see any reason why lean startup ideas shouldn’t be applied to the creation of a new language. Can you?

Kotlin and Ceylon to open their doors by the end of the year

sim city start

The residents of Java are waiting. Waiting for the day when another city will rise to supremacy in JVMland. These days they are looking north towards the functional territories and watch with interest as the new cities Kotlin and Ceylon are being built. Many Java inhabitants are tired of the city they live in. Not just since their home town is ruled by Amun, who is said to have just swallowed his predecessor Ra. For years they have been waiting for new facilities to be constructed. Facilities they have seen on weekend trips to other cities like the very hip Ruby or which they got to know and love while going to school in towns like Haskell. The people of Java are restless. While they are very familiar with their home town which provides all the basic features to get by, they are craving for some place new and exciting.

While it is not impossible the move to another city the adventurous have to bear some risks. New cities are having a hard time attracting companies to create jobs for willing new citizens. Often only companies in niche industries are willing to venture outside the secure boundaries of the Java megalopolis. Not few explorers who sought their luck in other cities eventually came back to Java because in the end it turned out to be more convenient. Big companies and with them their employees won’t even consider moving, before a new city has a proven success record. Many cities tried. Non succeeded so far.

The creators of Kotlin, still citizens of Java themselves, claim to have studied and learned from these failed attempts. They are promising all the best features from what is probably their biggest contender – Scala town – while having way easier infrastructure. They are also advertising stellar public transportation (aka Inter Domicile Express), which should help new citizens tremendously with getting to feel at home in the new environment. Like Scala they also aim for seamless communication with all districts in Java.

On first glance Ceylon’s layout looks very similar to Kotlin’s and some even suggest they should join forces to enhance their chances to succeed. But since the foundations of both cities are already done and dusted this seems very unlikely.

Kotlin and Ceylon are planning to open their doors by the end of the year and the weary inhabitants of Java are sitting on their packed bags – waiting.

The functional breakthrough … the back door

Back DoorEver since my first encounter with Haskell in my very first week at university I have been waiting for functional programming to become more widely spread and to find acceptance in the industry. Still… waiting…

Playing around with Scala these days, I have come as close as ever to use functional programming for something non-academic. Is Scala a functional programming language? You bet. But isn’t it also an object-oriented language? Certainly. Arguably more so than other object-oriented languages like Java (link). This might be the foot in the door for functional programming. Because object orientation is so dominant and functional programming requires such a different way of thinking, it is basically impossible for functional programming to compete with the market leader. And what do you do if you can’t beat them? That’s right. You join them.

Object-functional languages like Scala provide the perfect ground for programmers, who know their object-oriented languages inside out, to get to know the benefits of functional languages. You can get your code working by programming in the object-oriented way you live and breath, then you refactor it and add some functional touch to it. Or rather, you remove some of the wordy cumbersome cruft replacing it by more elegant code. And once you get to know and love the expressiveness that is functional code you will start writing it in the first place. And with that become a better developer.

By now, I have stopped waiting for a breakthrough of a pure functional language. But with that I am also sure that things like higher-order functions and pattern matching will find their way into the mainstream. One way or another.

Image by: So gesehen

Conway’s Game of Life in Scala

I attended a Code Retreat yesterday in Hamburg. As usual we used Conway’s Game of Life to practice our coding skills. I planned to do at least one session using Scala, but my Scala IDE wasn’t working any more, probably due to an incompatible upgrade of some description.

So, today I took the time to get my IDE up to scratch and implemented the game of life in Scala. It just had to be done. And since no-one forced me to delete my code after 45 minutes (as it’s common at code retreats) I actually got to finish it. Including console output. Bonus.

object GameOfLife extends App {
  var civilization = new Civilization(List((3, 1), (3, 2), (3, 3), (2, 3), (1, 2)), 10)

  civilization.printGrid
  for (period <- 1 to 100) {
    aGenerationPasses
    civilization = civilization.tick
    civilization.printGrid
  }

  def aGenerationPasses = synchronized {
    wait(100)
  }
}

class Civilization(seed: List[(Int, Int)], size: Int) {
  private val STAY_ALIVE = 2
  private val BE_BORN = 3
  private val grid = new Array[Array[Boolean]](size, size)
  seed foreach (cell => containsCellAt(cell._1, cell._2))

  def tick = {
    val nextGeneration = new Civilization(Nil, size)
    for (row <- 0 until size; col <- 0 until size)
      if (isCellAt((row, col)) && numberOfNeighboursFor(row, col) == STAY_ALIVE
          || numberOfNeighboursFor(row, col) == BE_BORN)
        nextGeneration.containsCellAt(row, col)
    nextGeneration
  }

  private def numberOfNeighboursFor(row: Int, col: Int): Int =
    areaAround(row, col) map wrap filter isCellAt length

  private def areaAround(row: Int, col: Int): List[(Int, Int)] =
    List((row-1, col-1), (row,col-1), (row+1,col-1), (row-1,col), (row+1,col), (row-1,col+1), (row,col+1), (row+1,col+1))

  private def wrap(cell: (Int, Int)): (Int, Int) =
    (((cell._1 + size) % size), ((cell._2 + size) % size))

  private def isCellAt(cell: (Int, Int)): Boolean =
    grid(cell._1)(cell._2)

  private def containsCellAt(row: Int, col: Int) =
    grid(row)(col) = true

  def printGrid = {
    println
    grid foreach {
      row => row foreach {
        cell => if (cell) print("*") else print(".")
      }
      println
    }
  }
}

The GameOfLife object runs the game by creating an initial civilization and then looping through a fixed number of generations, printing each of them along the way.

The civilization creates its next generation upon call of the tick method. This happens by applying (a simplified version of) the four rules of the game to each spot on the grid. Since I initialize the next generation with no cells, I only care about rules 2 and 4 that deal with alive cells.

Conway's Game of Life Rules

I decided to wrap the grid at the edges. So objects leaving the grid on the right don’t disappear, but re-enter on the left instead. This happens in the wrap method.

The numberOfNeighboursFor method is a bit magical. There is 6 method calls in a one-liner. Surely, people who are used to functional language list comprehensions can appreciate this. Read: In the area around the given cell coordinates (1) for each spot apply (2) the wrapping (3) then filter (4) by spots that contain a cell (5) and finally give me the length of the resulting list (6). Voilà.

I am not entirely happy about the use of a nested Array for the grid and the for loop in the tick method, but I couldn’t come up with a better solution. Suggestions welcome.

Follow

Get every new post delivered to your Inbox.

Join 167 other followers