Refactoring: like a clean kitchen

I once explained what refactoring was to a non-programmer. It went like this:

“We software developers (programmers for short) do not only need to write a program that accomplishes a task. That’s the easy part. The difficult part is to change an existing program to adapt to new requirements / problems.

A lot of thought has been put into this problem. Methodologies, advice, tips, books, best-practices arose and continue to arise to address this issue.

One such “practice” to address the “changeability” of a program is “refactoring”. Refactoring means that you change the way your program is structured inside, without changing what it does. It takes work, talent, insight and time, but ultimately it pays off. You are left with a better structure for your program and from there you can make changes more easily.

Imagine you just came from the super-market and bought a lot of stuff. Your goal is to prepare dinner for some guests. In front of you are the bags full of the ingredients you bought. Some other ingredients are somewhere in your kitchen. You still have some pans and bowls to wash from yesterday.

You could start cooking right away, and looking for each item as you need it, cleaning and making room in your kitchen as you need it, or brining an extra table from another room to occupy place in your kitchen because you are so focused on cooking that you don’t want to waste time making some order. Because you don’t have place to work, you take the new ingredients from the bags as you need them, and lay them on the floor.

You could work like that, because your mantra is “no need for tidying up, have to cook” but ultimately you will be less productive and the results will not be as good.

Instead, if you take time to bring your kitchen to a better “shape”, to wash, tidy up, prepare everything before you even start cooking, what looked as a waste of time pays off (because you know you will cook afterwards; if you won’t you can as well leave everything as it is).”

Setting up a simple Scala.js project

In this post I will guide you through the steps to start a basic Scala.js project. As a base we will use the Scala.js example application provided by S├ębastien Doeraene (Scala.js’ creator and lead developer).

Let’s say you want to have a Scala.js project called “My Project” (note the space between the words).

Step 1: Clone the exaple application

The example application can be found here:

You would use your favourite git-client to achieve this. Either through an UI-tool, or the command line:

git clone

Step 2: Rename folder

Cloning will have produced a folder caled “scala-js-example-app”.

Rename it to “my-project”.

Step 3: Modify build.sbt

Apply the following changes to the build.sbt file:

  • Change the name of the project to “My Project”
  • Optionally change the Scala version
  • Optionally add the jQuery-wrapper dependency

My build.sbt looks like this:

// Turn this project into a Scala.js project by importing these settings

name := "My Project"

scalaVersion := "2.10.4"

ScalaJSKeys.persistLauncher := true

ScalaJSKeys.persistLauncher in Test := false

libraryDependencies ++= Seq(
    "org.scala-lang.modules.scalajs" %%% "scalajs-dom" % "0.6",
    "org.scala-lang.modules.scalajs" %%% "scalajs-jquery" % "0.6",
    "org.scala-lang.modules.scalajs" %% "scalajs-jasmine-test-framework" % scalaJSVersion % "test"

Step 4: Generate and Import Project

At this point I tend to generate an IDE project, that I can import and work with. It makes things like changing packages, renaming classes, etc. easier.

In my case, because I use Eclipse (Scala-IDE), within SBT I type:

sbt> eclipse with-source=true

IntelliJ-IDEA users would type:

sbt> gen-idea

This pre-supposes that the plugins are accordingly configured in your system. Refer to the official documentation:

Step 5: Change the Main Class

Once the project is imported in the IDE, proceed to change:

  • The package of the main class
  • The name of the main class
  • Optionally, include the jQuery package
  • Optionally, write some demo code using jQuery

The resulting main class would look something like this:

package com.sebnozzi

import scala.scalajs.js
import js.annotation.JSExport
import org.scalajs.dom
import org.scalajs.jquery._

object MyProject extends js.JSApp {
  def main(): Unit = {
    jQuery("body").append("<h1>Hello from Scala.js using jQuery</h1>")

The IDE should have taken care of generating the corresponding folders.

Step 6: Change the HTML files

We can now begin generating the Scala.js code.

In the SBT console, run:

sbt> ~fastOptJS

This will activate the continuous compilation and give us valuable information for fine-tuning the HTML files. You should see some output like:

[info] Fast optimizing /home/sen/temp/my-project/target/scala-2.10/my-project-fastopt.js

This will tell you the location (note the Scala version!) and the name of the generated JavaScript file. Especially important is it when you use spaces in the project name, as we did.

Armed with this information, modify the HTML files accordingly:

  • Change the title of the host page
  • Optionally include the jQuery library
  • Optionally add other JavaScript dependencies
  • Remove the default HTML
  • Modify the URLs to the generated Scala.js files

The file index-fastopt.html would look like this:

<!DOCTYPE html>
  <title>My Project</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <script src=""></script>
    <!-- Add other JavaScript libraries here -->

<script type="text/javascript" src="./target/scala-2.10/my-project-fastopt.js"></script>
<script type="text/javascript" src="./target/scala-2.10/my-project-launcher.js"></script>


The file index.html would look almost the same, the only difference being the “opt” suffix at this line:

<script type="text/javascript" src="./target/scala-2.10/my-project-opt.js"></script>

Note that the “launcher” line remains the same.

Step 7: Verify

If all of the above steps were done correctly, upon loading index-fastopt.htmt you should see:

Hello Scala.js with jQuery


The best way to get started with a simple Scala.js project is:

  • Clone the skeleton application
  • Rename the folder
  • Change the SBT configuration
  • Change the main class
  • Change the HTML files
  • Include extra libraries

I hope this has been helpful. Let me know what you think and ask questions if anything is not clear.

Dealing with invalid Input

Recently I’ve been discussing about unit-tests and contracts, and the question arose if mechanism existed that would check at compile-time whether a value satisfied a certain condition or not.

This is a difficult question and no doubt a hot topic in computer-science research.

My intuitive answer would be: no. There can’t be such a mechanism, especially if those values are coming from sources we can not control. For example: user input, reading from a file, from a database, from a web-service, etc.

Since those values will be known at run-time, we are forced to deal with them at that stage. However, we can use our faithful assistance the compiler to remind us (even force us) to deal with these cases.

What do I mean? If we can model the situation where value is either valid or not with the type-system then we’ll have all the compiler assistance we want.


In Scala this is easily doable and in fact already part of the standard library. But nothing prevents it from being implemented in other languages as well (how easy or difficult this would be, is another question).

In this post I want to show you how to use Scala’s mechanisms to safely parse an Int, and how to guarantee at compile-time that it will be a positive Int.

Continue reading

Can Contracts replace Unit-Tests?


What are “contracts”? Contracts are the key element in the design-by-contract technique, natively supported by the Eiffel programming language.

They allow operate at many levels:

  1. methods: as pre- and post-conditions
  2. classes: as class invariants
  3. loops: as loop variants/invariants

In this article we shall only consider method pre- and post-conditions. That means, before method execution the pre-condition is checked and after the method is finished (upon completion) the post-condition is checked.

It’s an automatic runtime-enforced form of defensive programming. Recently I started debating with an Eiffel expert about unit-tests vs. contracts, his points being that contracts offer a superior mechanism over unit-tests. That discussion lead me to analyse his claims and write this article.


So the question is: can contracts replace unit-tests?

Continue reading

Integrating Cucumber and Play

In this post I want to show you how to integrate Cucumber into a Play (2.2.3) application.

It assumes some previous Play experience and that you know what Cucumber is about.

The example is minimal, but hopefully it is enough to get you started for bigger projects.

Setting up the SBT Plugin

Let’s start by setting up the SBT plugin. Add to “project/plugins.sbt” the following lines:

resolvers += "Templemore Repository" at ""

addSbtPlugin("templemore" % "sbt-cucumber-plugin" % "0.8.0")

This will make it possible for SBT to find and load the plugin. However, your project still lacks the corresponding settings (refer to the official page for a complete list). For this tutorial, we’ll be overriding some defaults. Add these lines to your “build.sbt”:


cucumberFeaturesLocation := "./test/features"

cucumberStepsBasePackage := "features.steps"

Continue reading

Scaladin chat demo in a Vaadin/Eclipse project

In this post I’m going to show you how to integrate a Scaladin project into an Eclipse-generated Vaadin setup. The demo I’ll be using is a small but impressive one: it uses Vaadin’s Atmosphere-poweredserver-push” and Akka-Actors (disclaimer: I don’t take credit, since I did not write the demo).

I like Scala, Vaadin, and find the idea of Scaladin excellent (to be able to code for Vaadin using idiomatic Scala). There is a SBT plugin for Scaladin, which integrates very well with this build tool. On the other side, the benefits of the Vaadin plugin and IDE integration are lost: like debugging in Eclipse, for example.

What I set up to do was modify the IDE-generated Vaadin project until:

  • Scala was supported
  • Scaladin was supported

As an excercise I “ported” (actually more like “copy-pasting”) the existing “Scaladin Chat demo” to the IDE-generated default setup.


Here’s what I did…

Continue reading

Scala Beginners: counting words and lines

A simple command-line tool

At work, I’m teaching one intern and one colleague how to program.

I gave them the following exercise:

Write an utility that takes 3 command-line parameters P1, P2 and P3. P3 is OPTIONAL (see below) P1 is always a file path/name. P2 can take the values:

  • “lines”
  • “words”
  • “find”

Only P2 is “find”, then P3 is relevant/needed, otherwise it is not.

So, the utility does the following:

  • If P2 is “rows” it says how many lines it has
  • If P2 is “words” it says how many words it has (the complete file)
  • If P2 is “find” it prints out the lines where P3 is present

Continue reading