Learning Objective-C the hard way

When I first started out at Xebia, I went with the safe and economical choice and got myself a giant Dell workstation laptop, instead of a fancy Macbook Pro like all the cool kids do. I even got Windows on it, but in retrospect, I hardly use Windows-specific features. Office? Don't need it. The rest? What rest? Outside of Office, there are exactly 0 programs I use that don work on Linux or Mac.

Except XCode and the iPhone development stack. There's a chance I'll be added as an extra to an iPhone development project, so I have to learn Objective-C and iPhone development - for which Mac is pretty much the only supported platform. Usually there's a Macbook one can borrow in such cases, but it wasn't available. There's alternatives in the form of setting up Hackintosh to run Mac on my Dell or run OSX in a virtual machine, but neither of those options are exactly legal.

Ergo, I had to make do for the moment, and learn Objective-C the hard way - outside of the cool kids corner Mac development environment.

Enter GNUstep

When you look for Objective-C development outside of the Mac world, all paths lead to GNUstep, an open-source version of the Cocoa API's and tools for as many platforms as possible. (The name is derived from Cocoa's ancestor, NeXTSTEP).

Installing the GNUstep libraries and tools on an Ubuntu system is simple, just sudo apt-get install gnustep gnustep-devel and you're all set (seriously, Apt is, as far as I know, the easiest way to install software - as long as it's in the repositories).

Next, you need to set up some system variables so that the GNUstep Makefiles can be located by Make. This is done through a GNUstep.sh file which, in the case of the GNUstep Ubuntu package is found in /usr/share/GNUstep/Makefiles/GNUstep.sh. (The GNUstep tutorial I followed indicated it was in some /System/Libraries folder, took me some searching to find it).

I added the line source /usr/share/GNUstep/Makefiles/GNUstep.sh to my ~/.bashrc file so it's automatically setup at boot.

So in theory,  building a project (once you've added the files and the GNUmakefile) is a matter of typing in 'make'. In my case, it wasn't - make complained it couldn't find a Makefile. Renamed GNUmakefile to Makefile, then it complained about there not being a GNUmakefile present.

Turns out I had named it GNUMakefile instead of GNUmakefile (notice the capital M.) Derp.

Renamed (again), ran make, ran ./obj/LogTest, tadaah, works like a charm.

Right Tools for the Job

Next up was the Quest for IDE's. It's probably common knowledge that XCode is the only proper Objective-C IDE out there, and it most likely is. The problem is that it's a Mac program, which is a bit of a problem if you run Linux (or Windows).

Looking around, Objective-C support seems shabby at best. Some people point to KDevelop, but it doesn't seem to have proper Objective-C support in the current (4.x) version. Others point to good old faithful Emacs or Vim, but one needs some time to adjust to those editors, as well as install additional scripts and files in order to get Objective-C highlighting and code completion. There's also a product under development by Jetbrains called AppCode, but - like XCode - it's Mac only. Why they didn't just build a plugin for IDEA is beyond me at the moment - the fact that it's Java and Apple's starting to get screwy with Java as of late might be a good reason though.

In any case. I haven't been able to find a fully-fledged IDE for Objective-C. KDevelop does partial code completion (probably based on how much sense it can make from the C / C++ bits in Objective-C), but it lacks syntax highlighting and indicates a lot of incorrect syntax errors in .h files.

So I guess that, for now, I'll just stick to plain text editors and the command line tools. GEdit seems to work just fine for the job, it's got syntax highlighting out of the box and no silly indentation issues. My commandline prowess and experience with barebones development using commandline tools like gcc and make is pretty low, so I guess it's a good exercise. Let's just hope that I get to borrow the Mac if I really have to do iPhone development. Maybe that'll make me a believer, too.

I'm pushing my Objective-C demo code to a public Github repository, primarily for backup and reference reasons, but who knows, maybe someone else can pick out some useful things from it. The repo is found at https://github.com/fwielstra/objective-C-tryouts

 

10 dollars of juice

People often say you can take analogies too far, here is me trying to do just that.

Farmer George is the proud owner of an orange grove. He has been happily selling the oranges, but now he has decided to take on a new service: orange juice.

Not knowing the size of the market, he quickly drafts the requirements of his new juice: it has to be refreshing, not too expensive, and have a refreshing color.

On paper, the request goes to different companies, the statement of work says: Get me 10 dollars of juice, it has to be orange and you will have to use my oranges.

The first company excepts without checking the quality of Georges oranges and with a simple orange press and one orange, they create an espresso cup of juice by hand. They then present the espresso cup of juice to George and request 10 dollars. George is not amused but in the end he pays 10 dollars for his juice.

George reviews his statement of work and adds: you must be able to fill this cup, stapling a plastic cup to the statement.

The next company brings their own spring water bottle to the job, and combines 2 dollars of spring water with a new hand pressed espresso cup of real orange juice. Again, George is not amused: even though the orange juice is refreshing, the right color, and the right amount, it does not taste like the quality he was after.

The next company brings in their own automated juicer, which they have used at other companies as well. They put in Georges oranges, but because the oranges of George are not as good as they expected, they almost use up a whole crate of oranges to fill the cup. George is charged 10 dollars, but he never expected he would have to put in 50 dollars of his own oranges. George is not amused: he has gotten a solution that simply won’t scale.

Now at this point, George could amend his statement of work to include using at most 4 dollars of my oranges and find a company willing to risk the job without knowing the quality of Georges oranges. But not even George knows the quality of his oranges when it comes to juicing, so any company taking it on will just have to accept that risk.

However George could also conclude that using his statement of work as a body of knowledge between different contractors is not the best option. If he would have had a company which would stick with him through all those ordeals, he could have been paying 10 dollars per improved version with the added benefit of having a team that knows about the previous failures.

The multiple return arguments argument

When new languages appear, like Scala, people start raving about the language features that give you the freedom to do things with less characters. One of these things is multiple return arguments. Generally speaking it is the ability to assign values to members of anonymous containers (often only a tuple).

I’ve convinced myself that if I feel like I need multiple return arguments to work in a language, that I’m not creating a proper API. Only problem is, have I just convinced myself or is my argument convincing? Here goes.

People coming from more dynamic languages like Python, PHP, Ruby, Javascript and now Scala have come accustomed to be able to use multiple return arguments by initializing a tuple with the return value of a function. Say

(book, location) = bookcase.firstShelf.grabFromShelf(12.th.book());

Looking at only this example, two sides of an argument can be quickly listed. The dynamic/messy people will say:

It feels nice and terse to get two local variables initialized with a single function call/assignment. The grabFromShelf member has to do the lookup anyway, so why let the location go to waste? Having to create a type to return a collection like that is just extra work. Naming a type for each of these kinds of calls is even harder. Did you know it comes in handy when you want to add a succeeded/failed status boolean to the return code?

The other side, the sluggish/clean people will say:

One function, one responsibility so it should never have to return more then one object It’s better to have a clean design then trying to saver every cycle. Ever heard of premature optimization? If the data you return cannot be placed in a single variable/class, it should not be returned together. Naming should not be a problem if you have a good OO design. Adding a succeeded/failure status boolean is stupid, failure should be an exception.

And it is this last point which I would like to take a closer look at. Specifically the FileNotFoundException. The two APIs are:

(file, success) = open(filename)

and

if(File(filename).exists())
{
    file = open(filename);
}

The first example just tries to open the file and if that fails, success will be false and file invalid or a closed File object. The second example will test for the existence of the file and consider failure beyond that point an exception.

First thing that you may not like about the second piece of code is that it clearly states a race condition which is caught by an exception. If the race condition occurs, the programmer will be a bit stupefied by it because the code seems to say: only try to open the file if it is actually there. If you feel this is the case, you might prefer:

try {
    file = open(filename);
} catch(FileNotFoundException e) {
    //Handle the no success case
}

I think this last step, using try catch block, will split the scope of your success and failure handling code and will probably make your life more difficult: how much code will go into the try block, how much code will go into the catch block.

I think checking for file existence, opening the file and passing the Exception up in the tree is the best way to go. The first version may return a useless parameter (file) if it failed to open the file and the function would be better off returning an object with the right members, making the API more self-documenting.

I think the second piece of code also has a lesson: if you feel like exception handling is cutting up your scope to much, use state checking to promote the Exception to a real exceptional case. After that, I don’t see why you would have to have multiple return argument support anymore. It may be handy, but it certainly is not a feature I would consider exciting when choosing a new language.

Dependency management in NodeJS

First off, I'm not sure if this is the correct title to this post, because the title can refer to two things: indicating a dependency on external packages outside the scope of your project, and the 'application-internal' dependency management business. This post in particular is about the internal variation, or how to make your modules loosely coupled.

An alternative title might very well be 'How do I make my modules (unit) testable?', because that's specifically why I went to research this particular subject.

The situation is as follows. I have a simple application that's built out of a handful of components: the application itself (performs intialization of the webserver), the 'controller' (defines routes and handles them), and finally a 'model' (defines a schema and provides access methods to MongoDB). I initially built these based off of the examples found all over, on top of the Express framework and the Mongoose ORM. This resulted in roughly the following code:

Click me for code!

Looks about right, right? Well yeah, but there's a few things going amiss there, particularly in the controller and the models. The problem with the above code is that it's difficult to test. If I want to test the three methods in the controller, I actually need to mock logic contained in the Thread and Post models - I can't mock the Thread model from the outside to provide a mockup of the findOne method, for example.

Or well, I can, actually, but then I'd have to provide a separate Thread.js for testing purposes and rewire the Node include path to include that one. It might also be possible to override the require() method, but do we really want that? Imagine if I suggested to an experienced Java guy that, in order to test our class, we had to provide a custom classloader. Wouldn't go. In Java and most other programming languages, we'd provide our controller with mock objects instead - in this case, a thread service of sorts.

In this case we don't have a separate Thread service, but it's part of Mongoose's model definition (following Ruby / Rails paradigms). In any case, we need to replace the Thread inclusion in our controller. How? Well, that's what I wondered too. I ventured forth to Google, and found this blog post on Citysearch Australia's code monkey blog.

It indicates a 'pattern' of sorts that allows us to effectively inject dependencies on the Thread and Post models into our Controller. Here's how that looks:

You'll notice that the public API of the controller hasn't changed, even though internally it looks rather different. Javascript magic, right there. With these rewrites, we can write a unit test too, easily mocking our Thread and Post models. Here's a simple example of how we could call our controller with a mocked Thread and Post model:

And that's how you do dependency injection in Node. Roughly. I think. I'd just like to note that the unit test is rather large, and mainly composed out of creating mock objects. I'd like to know from any readers if they know of a better and / or more concise method, or whether I'm actually doing it right here. On the one hand, I quite like that with Javascript's type system, you don't really need a mocking framework - you can just replace a method somewhere and you're done. No interfaces either, so no contracts you have to adhere to. The script interpreter will just throw an error if you provide an object that doesn't supply a particular field or method. You can literally hide away hugely complex affairs behind a simple mocked object. It's quite powerful, actually.

I really wonder now what else Javascript has in store. I can imagine why people get excited over using Javascript on the server-side. Next up on the reading list is looking up some Javascript design patterns, such as Essential Javascript Design Patterns by Addy Osmani.

 

First steps with Sammy

I started to learn myself NodeJS a week or two ago, and after the first handful of tutorials, decided I needed a project of sorts as a guideline to learning the subject. Being unoriginal, I settled for something common - forum / messageboard software. Being even more unoriginal, I portmanteau'd Node and Forum together and called the project Norum.

The general architecture is not dissimilar from my previous project at UPC, which had a storage layer, a (simple) controller layer, and all the rendering logic on the front-end. In that project we used Backbone.js, which, I think, would also be suitable for this project. Backbone is, however, a bit 'bureaucratic' - you need to define a model, view and controller for just about anything.

So instead of sticking to what I already knew, I started out by looking around at alternatives to Backbone in order make a simple POC for it, see if there's something out there I like better. I'm not sure exactly how, but I came across Sammy, a front-end web framework built on top of JQuery. It advertises itself as being small (5.2 KB compressed / gzipped), modular, clean and fun. Of course, I had to put that to the test.

There's a two-part tutorial to get you started, which I followed, making changes here and there to use my existing webservice (for retrieving and storing threads). The tutorial itself uses a static .json file to retrieve the data.

First steps

Initializing a Sammy application entails attaching it to an element in your page and provide a callback method that attaches your routes. In that aspect, a 'sammy app' (as we'll call it for now) is effectively a controller in MVC terms.

Finally, you need to initialize your Sammy app by calling a run method to indicate what route to open up first. Below is an example of 'My First Sammy App', which should be stored in a separate .js file (or script block, but I prefer storing it in a .js file). It uses the Javascript Module Pattern to make sure all our application's variables and functions are contained in scope.

Does the above make sense? I still need to look up the exact specifics of the Module pattern and what it is exactly doing with the (function($) {})(jQuery); - statement, but for now it's safe to assume that it compartimentalizes your app's logic, executes it once it's loaded, and (maybe) passes the jQuery object to the inner scope of the code fragment.

Retrieving and displaying data

Loading data can be done through jQuery, using the $.ajax() method and its derivates, but Sammy also provides an alternative with the load() method. The documentation on the method is sparse and I'm not sure I fully understand what it's supposed to do exactly, but looking at the actual result, the load method simply does an AJAX request on the given resource. Here's an example of how I use it in my application:

Sammy has a handful of template modules, including Haml, Meld, Mustache, Pure, jQuery-tmpl and its own Template - choose whichever you prefer. In this case I just followed the example and used Sammy's 'native' template module, which is a pretty classic template language in that you put code blocks in between your HTML. Here's my current / preliminary template for displaying a 'thread':

But I still need to dive deeper into the various available alternatives, so this may not be the optimal template type to use. Still, it looks very familiar, and shouldn't take too much time to adjust to - which is also an important criteria for selecting a template language.

So far, so good.

Storing data

Saving data (by doing a POST-request on the API) isn't in the tutorial I followed - it uses the Sammy.Storage plugin, which acts like a session storage (but internally is a wrapper around a bunch of technologies like HTML5 DOM Storage, cookies and jQuery.data). Clientside storage, basically.

This wasn't what I needed, so I went ahead and tried to do a POST request towards my own webservice. This is where the Sammy API, examples and tutorials are unclear about. There's no (obvious) POST-request to a back-end webservice in any of the examples, and the API documentation isn't very clear either. There's the load() method that retrieves data, and one would assume that the send() method does the opposite - i.e. store the data to the back-end. But it doesn't.

To date, I haven't figured out how to do a POST-request in the 'native' Sammy.js fashion. Instead, I fell back on jQuery, which actually works just fine without looking particularly nasty. Here's the save method in my POC:

It fires off a POST request and instantly redirects the user to the 'display' route. I should probably rewrite it so that it shows a spinner and only redirects once the POST-request is done though; it works fine on my local system, but I'm sure things would become quirky if there's more of a delay between the client and back-end (users getting 'thread not found'-errors due to the thread not being saved yet, that kinda thing).

In any case, that's how far I got. Sammy looks promising, but could do with clearer documentation and more guides on how to perform certain actions the right way. There's only four example applications and a two-part getting started tutorial, and the blogposts about it I found online don't really go beyond a first introduction (this particular post is no exception to that, by the way).

Compared to Backbone

So far, I think I like it more than Backbone because it's less 'official', so to speak. I don't have to define a View or a dedicated Model for my data, but just throw it out there in the controller. With Backbone, we tried to do it the official way and ended up with models defining only an 'url' method (which indicates where Backbone should get its data from) and boilerplate code to extract the relevant data back from the model again and pass it to either Mustache or Datatables. Calling Mustache and Datatables was, of course, contained in another boilerplate View object. Here's a sketch of how that would've looked in this application (hacked up just now, may be incorrect):

Compared to what the Sammy implementation looks like, Backbone's approach just looks very boilerplate-heavy. Here's the Sammy equivalent:

On the one hand, Sammy's notation is more concise and 'direct', so to speak. On the other, there's a lot of nesting going on, even 'custom' nesting in the chained methods to try and keep things organized and logical.

When it comes to Backbone versus Sammy, right now I think Backbone is the more officially structured of the two, wich allows for a highly modularized application codebase, whereas Sammy is the more compact of the two, employing various tricks to produce concise code.

At the moment, I think both have their quirks, and neither is as properly documented or intuitive as I'd like them to be. For now I'll continue with Sammy on my project, because, besides a short hiccup with posting data and wondering how I'll keep things organized as my application grows, I haven't had any serious complaints with it. Still, right now I think Backbone will allow for a more structured and reusable API.

I should still check out and compare the two in combination with CoffeeScript. This tutorial for example shows a few CoffeeScript tricks to reduce the boilerplate code in a Backbone script (for example by removing the need to call _bindAll()).

To be continued.

(This entry was partially crossposted on my personal Tweakblog)

Code as fast as you think with Zen Coding

A lot of people write HTML, XML, or a similar data-structuring format. A lot of people don't particularly like it either. Some will like it, but for the wrong reasons - I personally find doing anything on my keyboard oddly gratifying, independent on the actual 'worth' per keystroke.

Writing out HTML and similar types of code can be a typing-intensive task. Writing out something like <div id="main"></div>, for example, takes six combination keys (shift+., shift+') and a repetitive task (closing the </div>), while the basic idea you're trying to write is 'a div with id main', or in your most basic thought patterns, 'div main'.

Yet many people write out the full HTML section, because they either don't know of an alternative, or don't actually want an alternative, and the basic act of writing out a HTML structure gives them some gratification and a feeling of doing something relevant.

Well it's not. There is an alternative, and it's even faster than an IDE that automagically adds a HTML closing tag (saving two combination keys, a slash and a couple of characters). This is Zen Coding.

Who knows CSS Selectors? If you've ever worked with CSS or jQuery, you will. A CSS selector is bascially a syntax that allows you to specify a certain portion of your HTML document. You can 'select' a div with ID 'main' using the CSS selector div#main.

When you read div#main, and you're somewhat versed in basic CSS selector syntax, you will recognise this as 'A div with ID main', and read it as 'div main'. Wait, doesn't this seem familiar? Yes, a few paragraphs back, it turns out this is the same thing you have in your mind when writing out the full HTML for creating a div with a certain ID.

Zen Coding recognises this too. Zen Coding is an editor or IDE addon that allows you to write HTML by writing CSS selectors (and a few additions), allowing you to replace the boring task of writing out HTML syntax with writing out your thoughts with some minor syntax.

I can demonstrate this with a handful of examples. If you want to go along with this, you can use the online Zen Coding tool at http://zen-coding.ru/textarea/, or go to http://code.google.com/p/zen-coding/ and get the editor or IDE plugin of your preference to add Zen Coding support to it. I discovered this feature in IntelliJ IDEA, as it's a default feature in this IDE.

HTML tags

To start, let's create a div. In your editor, simply type div<tab>, where <tab> means 'press on that button on your keyboard that says 'tab''. This produces the HTML <div></div>, and places (in the case of IntelliJ) the caret in the middle of the div, so you can immediately write out the contents of the div.

ID attributes

Give the div an ID. Delete the div, then recreate it using div#main<tab>. This produces a <div id="main"></div> - a six control+key and 14 regular-keystroke string in just 7 regular and one control+key keystrokes. It types much more natural, too, as having to do ctrl + < takes some acrobatics (if you're like me and try to do the two keys with the same hand).

Classes and combining

Similarly, we can give the div a class instead. Simply type div.content<tab> to give it a class 'content'. Of course, you can also combine the two - type div#main.content<tab> to have the editor write out <div id="main" class="content"></div> instantly.

Attributes

Perhaps unsurprisingly, you can add a non-class or ID attribute to an element using CSS (or XPath?) syntax. Let's write a div with a role: div[role=main]. This produces a div with a 'role' attribute with the given 'main' value.

Children and siblings

The CSS standard also supplies syntax for children and siblings. If we want to create a div that contains a fancy HTML5 nav element, we can use that:

div#main>nav

produces:

<div id="main">
    <nav></nav>
</div>

with the caret inside the <nav>-tag. Similarly, we can add siblings. Let's add a list to the nav tag:

div#main>nav>ul>li+li+li
produces:
<div id="main">
    <nav>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </nav>
</div>

This puts the caret in the first LI. In my editor (IDEA), pressing tab again moves the caret to the next li - no reaching to the mouse (as I often do) to move to the next list item.

Multiplication and numbering

We repeated the three LI siblings by typing out li+li+li, which can be written out pretty quickly, but it can be done even faster using the *-character. Note that this isn't the CSS *-character, which matches all, but a Zen Coding-specific character. Instead of writing li+li+li, you can write li*3, which produces three (sibling) list items.

If you like, you can also number the list items using the $-character. Try this: ul>li#item-$*3. This produces a neat list with three unique ID properties in the list:

<ul>
    <li id="item-1"></li>
    <li id="item-2"></li>
    <li id="item-3"></li>
</ul>

Grouping

Finally, you can group sections of your Zen Coding string using parentheses. Read the next Zen Coding string and guess what the outcome is:

html>(head>title)+body>(div#header>img)
<html>
<head>
    <title></title>
</head>
<body>
    <div id="header">
        <img src="" alt="">    
    </div>
</body>
</html>

Zen Coding allows you to write a large amount of largely boilerplate HTML in a concise syntax that's almost as fast to write out as you can think. With a one-liner like the following, you can write out a full HTML page that would normally take you five or so minutes to write out in the classic fashion:

html>(head>title)+body>(div#header>img)+(nav>ul>li*2>a[href=article-$])+(div#main>(h1>span)+(article*2>(header>(h2+time))+summary+section*2>h3+p)+div#footer)

Once you're used in the syntax, producing large amounts of HTML - if needed - becomes a trivial matter, and it's much easier and faster to experiment and change some things around.

Of course, I wouldn't recommend even trying to write out a Zen Coding string like the above - I admit I spent five minutes or so trying to debug it because I had the parentheses wrong. Instead, try to write nice and short 'sentences', if you will. Split the above up into:

html>head>title
body>div#header>a>img
nav>ul>li*2>a
div#main
article#2>(header>(h2+time))+summary+section*2>h3>p
div#footer>nav>ul>li*5>a

etcetera. It's a matter of style.

Other applications

HTML isn't the only thing you can do with Zen Coding. Naturally, you can do XML and XML-like structures too with the same syntax. There's also alternative applications for zen coding, for example with filtering. One example is the 'e' filter, which escapes the HTML output like so:

div#main|e

produces the HTML-escaped version:

&lt;div id="main"&gt;&lt;/div&gt;

Another is the 'haml'-filter:

div#main>nav>ul>li.item*3|haml

which produces the output as a (also concise but rich in whitespace) HAML template:

#main
  %nav
    %ul
      %li.item
      %li.item
      %li.item

I'm pretty sure there's other output formats out there too.

Writing CSS isn't that big of a chore, but it can be done faster. Writing out 'margin-bottom:auto; can really slow you down if you want to chuck up large amounts of CSS lines. There's a Zen Coding derivative, Zen CSS properties that helps with this. With shortcuts like mb:a, you can write out full CSS properties a lot more efficient. See the webpage for more examples.

Another interesting application is using Zen Coding with some rudimentary syntax extensions as a template language. One limitation of the basic Zen Coding syntax is that you can't add values to the output - adding this option makes it suitable as a very compact and powerful templating language, not unlike the above mentioned HAML and its derivates. Here's an exaple from the JQuery Zen Coding plugin:

var data = {
  contacts = ['Bob', 'John', 'Yog-Sothoth']
}
$.zc('h2{There are !contacts.length! contacts.}', data);

which produces:

<h2>There are 3 contacts.</h2>

One thing to keep in mind though: anything longer than 40 characters or so becomes hard to read and maintain. A multi-line, but similarly compact syntax would be more suitable for longer templates. Partial templates could also help, so you can keep the individual templates short.

With client-side templating on the rise, a short but readable syntax for creating templates is certainly worth exploring.

tl;dr

In hindsight, modern IDEs sorta offer similar functionality with pre-defined templates, but they're not as flexible as Zen Coding - yes, you can chuck out a default navigation block with IDE templates, but you have to pre-define them, and you need to manually edit them afterwards if you want to change some IDs. I believe the zen coding logic can be applied to a lot of areas, especially in potentially code-intensive languages. I also think it's a very smart alternative to what we know as IntelliSense, automatically filling in the full name of the function you want to use.

Currently, at least for me, this involves typing part of the function name, and then either waiting a few hundred milliseconds (I think I have it set to 200 at the moment, but I'm not sure) or pressing the ctrl+space keyboard combination. This often - at least in the case of Eclipse - leads to having to wait a short while until the IDE has loaded the available functions.

With Zen Coding-style syntax, you could possibly type part of the name of a class or feature you want to use (or use the abbreviation-style already possible in Eclipse, for example typing IAE if you refer to an IllegalArgumentException), and just put it there instead of still offering you a choice and you having to press enter. I can imagine typing 'for 1 to 10' in Java, then pressing tab to have it written out as a proper for-loop with all the syntax, could speed up productiveness.

I might just be misusing my IDE though, or not using some smart customizations like having tab double as ctrl+space or return.

tl;dr: Zen Coding, It's Good™.

Book review - How to win friends and influence people

I'm not big on self-help books. After the Xebia Bootcamp, I was given a stack of books that, quite frankly, made me a bit queasy. Oldish businessmen with a smug smile and big keywords plastered across them like "Winning!", "Success!", "Smugness!" and "My Shit Don't Smell!".

The generalized view I have of self-help books is one of faking it. The bigger the title, the worse.

Still, I started reading one from the stack ("Seven Habits of Highly Effective People", or my personal view before actually reading it, "Seven Simple Black Magic Spells to Own at Everything You Do."), and whilst it's rather full of 'power sentences' and repetition, it does have some good points about the human psyche, how people think, andsoforth. Whilst understanding of these principles were already present in me, it required this book to confirm them and put them into words.

But this blogpost isn't about that self-help book, it's about a much, much older one - in fact, it's the first widely popular and best-selling self-help books of all time. I'm talking about "How to Win Friends and Influence People", a book published in 1937, written by Dale Carnegie, who became a widely popular speaker drawing full rooms of high managers back in his time.

This book can actually be read as a psychology book, or how people work, how people perceive what you tell them (and how you perceive what others tell or do to you), and what you should do to, amongst other things, gain friends and healty contacts, interact with people in a pleasant fashion, and (rather deviously) bend others to do your bidding - and without threatening them with eternal torment and/or five minutes on the naughty chair.

"Wait a minute," I hear you think, "This personal interaction business is not relevant to my interests, *closes tab*". Well, actually, it is. Well maybe not if you're the assemby line-type developer (requirements come in, code comes out) (which, by the way, means you've achieved robothood - congratulation! A winner is you!), but if you're like what the rest of us is (or strive to be), you're more than just a developer, you're a consultant. You're a team member. You might even be a Scrum Master or Project Manager or even Some Guy That Chats With Some People Sometimes To Humor Them.

In these cases, this communication skills thing is actually quite relevant. In fact, even if you don't engage in verbal communication (much or at all), these communication skills will be quite essential in your written communication - think emails, IM, but also asking and answering questions on StackOverflow or posting on the People That Dress Up As Orcs In Their Spare Time website.

The book is, at least the first few chapters I've read so far, largely built out of anecdotes and examples from the author - things he's experienced, stories from the attendees of his courses, and examples for applying the relatively simple lessons and principles he lists in his book.

You'll note I said the book was published in 1937. I'm sure you'll think "Pah! That's pre-WW2, that no longer applies to people in this day and age!" or "Pah! I don't want to read through archaïc ye olde English with thees and thous sprinkled with thines, that doth not be of relevancy towards mine interests!", but you'd be wrong on both counts.

First, you're wrong because the basic principles of human communications is as old as communication itself - be it eloquently spoken words or the bashing of fists against chest. Similarly, the lessons and principles taught in the book apply to all forms of communications, be it verbal or otherwise, archaïc ye olde English, street slang, or teh l4ngu4g3 of t3h internets.

Second, you're wrong because it's quite readable, it's been revised several times over the years, and pre-war English isn't that different from English as it is today.

Third, I told you you were wrong several times in the past few paragraphs, and thus broke rule #2 in the section about winning people over to my way of thinking. Therefore, there's a good chance you're already - conciously or subconciously - rebelling against my post and my intention of getting you to read the book.

But hopefully, with the paragraphs leading up to it, I've encouraged you to read the book by applying principle #3 from the "Fundamental Techniques in Handling People"-section - "Arouse in the other person an eager want". This is summarized by: if you want other people to do what you want, make /them/ want it. I can tell you to go polish my shoes, but chances are, you won't. On the other hand, if I offer you €100 to do it, you might reconsider as the action will provide advantageous to you.

There's dozens - if not hundreds - of anecdotes, stories and examples in the book that all outline these basic principles and guidelines.

So right now you might be thinking "Oh shit, I need to go read this book and wrestle through hundreds of anecdotes!", but actually, you don't - there's a Wikipedia article that outlines the book, and each sentence in the outline should make perfect sense to you.

Here's an exercise to the reader. Read each of these following tips, principles and rules, and think of an example or, better yet, a practical application or example from your own (recent) experiences. Also think of something you've said to someone or something you tried to achieve without success, and what you would have said keeping one of these principles in mind. Particularly the first fundamental technique in handling people (don't criticize, condemn or complain) is very difficult to do, as it's very, very easy to criticize and complain.

There's also a hidden lesson in that principle: Don't criticize, condemn or complain to yourself. Instead of thinking "Shit this blogpost I just wrote sucks balls and I should never have posted it", you'd be better off thinking "How could I further improve this?" or something to that effect - instead of living in the past with decisions made, think about the future and the things you still can influence, that still matter.

Anyway, here's the list:

 

Fundamental Techniques in Handling People

  1. Don't criticize, condemn, or complain.
  2. Give honest and sincere appreciation.
  3. Arouse in the other person an eager want.

 

Six Ways to Make People Like You

  1. Become genuinely interested in other people.
  2. Smile.
  3. Remember that a person's name is to that person the sweetest and most important sound in any language.
  4. Be a good listener. Encourage others to talk about themselves.
  5. Talk in terms of the other person's interest.
  6. Make the other person feel important - and do it sincerely.

 

Twelve Ways to Win People to Your Way of Thinking

  1. The only way to get the best of an argument is to avoid it.
  2. Show respect for the other person's opinions. Never say "You're Wrong."
  3. If you're wrong, admit it quickly and empathically.
  4. Begin in a friendly way.
  5. Start with questions to which the other person will answer yes.
  6. Let the other person do a great deal of the talking.
  7. Let the other person feel the idea is his or hers.
  8. Try honestly to see things from the other person's point of view.
  9. Be sympathetic with the other person's ideas and desires.
  10. Appeal to the nobler motives.
  11. Dramatize your ideas.
  12. Throw down a challenge.

 

Be a Leader: How to Change People Without Giving Offense or Arousing Resentment

  1. Begin with praise and honest appreciation.
  2. Call attention to people's mistakes indirectly.
  3. Talk about your own mistakes before criticizing the other person.
  4. Ask questions instead of giving direct orders.
  5. Let the other person save face.
  6. Praise every improvement.
  7. Give the other person a fine reputation to live up to.
  8. Use encouragement. Make the fault seem easy to correct.
  9. Make the other person happy about doing what you suggest. 

 

I guess the outline starts with the most important principles first. You will read the first three and, if applied properly, the rest of the book's principles will follow naturally. I think all of these make perfect sense, and I'm just glad there's a book out there that describes them in an easy-to-follow and logical fashion.

Because both the book's copyright and its author have expired, the book has fallen into public domain and can be downloaded in one way or another all over the internet. Here is a nice version. Chuck it on your ebook and, at the very least, glance over it once in a while.

Running Selenium tests with multiple WebDrivers

We decided to use Selenium to run front-end integration tests for our current project, and I was charged to investigate, seeing that nobody in the team had ever worked with Selenium before. I did, for my previous employer, but it was limited to playing around with Selenium IDE for a day - we never found the value in developing a full integration test for the dozen-or-so corporate websites we managed, in part because we didn't really know /what/ to test.

In any case, I did some browsing and, as it turns out, Selenium 2.0 is under heavy development, currently in beta stage. Selenium 2.0 is the combined effort to merge the original Selenium project with the WebDriver project, a means of running Selenium tests from (Java) unit tests, which 'remote controls' a browser running on the local system. Here's a simple example of what a Selenium test with WebDriver looks like:

It looks quite straightforward - you instruct WebDriver to open up a browser window by creating a new implementation of WebDriver, send 'commands' to it, evaluate responses, andsoforth. When running the test, you will see a browser window open and various actions being performed, based on the input from the unit test. Finally, by calling WebDriver.close(), the browser window is closed.

Now. A good integration test will run the tests on each officially supported platform. In our case, this would be Internet Explorer 7 and Firefox version 3.x. Ideally, we would run the integration tests against these exact platforms, however, our team turned out to be too modern - I was the only Windows user, and already was at Internet Explorer 9. The others had all upgraded to Firefox 4. Compatibility problems ensued. Initially, I had added Selenium 2.0a4, but as it turns out, the WebDriver(s) in that version didn't support either IE9 or Firefox 4.

We were at a standstill for a moment then, but after some creative Googling and a 'duh' moment, it turns out we were horribly outdated. A few versions later, version 2.0b2, Internet Explorer 9 and Firefox 4 support was added.

On to the next problem. I considered it a good thing to run the integration tests on all supported platforms, so I first devised a structure that retrieved a list of WebDrivers to run all the tests with. This became a factory-like class as you see below. It returns a List of Supplier objects, one of Google's utility interfaces that does little else than return an instance of an object, making it suitable for use as a factory, generator, builder, closure, or something else entirely. Each Supplier returns a new instance of its matching WebDriver when called upon.

Using all the registered WebDrivers in an integration test involved running the body of the tests in a loop, for each WebDriver, run these tests. I'm still wondering if there's a neater solution for this, an annotation maybe that indicates to 'run this test using all registered WebDrivers. But this will do.

Of course, we don't want errors to occur when people without Internet Explorer try to run it, so we added a line that makes sure the IE WebDriver is only added if the user is running Windows:

This worked. For each integration test, a new, fresh browser window was opened, the tests were run, and the window was closed again.

Of course, it wasn't done yet. First, creating a new browser window and session for every test takes a (relative) large amount of time, making the integration tests run for at least twice as long as they should. Second, the Java binary crashed when it tried to start up an Internet Explorer window for the second time. It's known that you can't open two IE windows at the same time with the Selenium WebDriver, but it crashing when opening two windows in the same JVM session is, as far as I know, not a well-known problem.

Of course, we could solve two problems in one stroke by simply re-using the same browser windows for every test. Because we already had a factory structure in place, this was a matter of storing a single WebDriver instance in the Supplier class, initialize it on first call, and return it on consequent calls. Note that the following solution isn't threadsafe.

Considering this is the solution we've been using for a couple of weeks now, I'd say it's done. I hope other people will find this post useful - I myself wasn't able to find any examples for running Selenium tests with multiple browser types.

Some final notes on Internet Explorer and Selenium:

Clicking links and buttons through WebDriver in Internet Explorer turns out to be a tricky business; adding various hacks in the integration tests themselves make it workable, but it's far from ideal. See http://stackoverflow.com/questions/4737205/selenium-webdriver-ie-button-issue for a SO question about this issue. We've added a click method of our own as a workaround to this issue - it can click on any clickable element using the WebDriver syntax (the By parameter).

I wasn't able to find out how to instruct Selenium to activate IE 7 compatibility mode in Internet Explorer 9, a requirement for making sure the test works properly in IE 7. One possible solution (and at the moment, the only solution I can see) is to include a meta-tag or HTTP header telling IE to run the site in IE 7 compatibility mode. However, this is a step easily forgotten when going to production, and may cause problems in the future, when people try to run it in IE 13 that, with any luck, no longer provides backwards compatibility with its old and quirky renderers.

Daily rant: Java Dependency Hell

Today, me and Iwein were doing a little trial to see if we could integrate EXI, the new Efficient XML Interchange standard from the W3C, into Spring Integration. It’s a bit of a niche standard right now, but I personally believe that it could have a big impact in all areas where XML is used in one form or another. Read the EXI primer or a blog I made on my personal blog a while ago for more information on EXI.

 In any case. Currently, as far as we could see, there’s two libraries out there that work with EXI and are feasible in our project: EXIFicient, a GNU library used in the evaluation stage of the EXI development process, and OpenEXI. Since EXIFicient seems to be the most mature and actively maintained one, we went with that one.

 In theory, it works fine – does what it needs to do, simple and easy to read and use API, etcetera. The problem with EXIFicient, however, is dependencies. Some history.

 A long, long time ago, Java projects and dependencies were both pretty tricky, but, as long as everything was properly documented, it just took a lot of time to get a project set up. Then came along Maven and similar tools like Ivy, which, along with centralized and distributed repositories, made things a lot easier – just add some metadata that says which library and what version thereof you need, and you’re done. Automatic resolving and downloading of libraries, and all you have to do if you’re starting to work on a project is wait for the dependencies to finish downloading (which could be done a lot faster, imho, but that’s for a different rant).

 EXIFicient (and its competitor, OpenEXI), don’t do this, though. They both have very little dependencies – both rely on Xerces – but getting it to run inside a Maven project isn’t easy. Remember when I said that it was doable as long as everything’s properly documented? EXIFicient didn’t. Or well, they did – they indicate in their readme that Xerces 2.9 or higher is needed. So, me, naïve as I was, just added Xerces 2.9(.1) to my pom.xml, and started to work with it.

 Of course, it broke. Turns out that EXIFicient uses a XSElementDeclHelper somewhere, which, as the API documentation thereof states, probably shouldn’t be used. So, it seems EXIFicient uses a version of Xerces that happens to have this class declared somewhere, but exactly which version remains a mystery.

 I must note that Xerces itself isn’t without blame either. Xerces is a very old Java library, from way before us young ‘uns were even born (or something), and as such it doesn’t do Maven support either. New releases of the library take ages to get into the Maven repos – case in point, latest version in the Maven repo is 2.9.1 (October ’08), whilst the latest version is 2.11.0 (dec ’10), and pushing releases to the Java world’s largest dependency management system’s repositories is simply not a priority for the Xerces team (or not part of their release plan). And that’s a shame.

The follow-up: I had to apply dirty hacks to get it to work. Installed the xercesImpl.jar and xml-apis.jar libraries into my local Maven repository with a custom version, and referred to those in my pom.xml. I'm going to stand in that corner over there now.

Must-read blogs: Rands in Repose

I must admit, I'm not much of a blogger. I never made a habit out of following blogs or people, and I could never get into RSS readers or some other technology hip people use to stay up to date.

Nevertheless, this doesn't mean I don't have a deep appreciation for some of these blogs and the wisdoms contained therein. I should add a list of good weblogs to the Reading List on this site. These will most likely start out to be the ones everyone knows about already (I mean, everyone somehow fawns over Joel Spolsky, Jeff Atwood, and a bunch of others), but I hope to add some that are less known but still must-reads soon.

One particular blog is one I feel needs separate, special attentions: Rands in Repose. Perhaps surprisingly, this particular blog isn't about software development (or, not directly), the hippest new programming language, the One Framework to Rule them All, or the “look I had a problem and this is how I fixed it”-posts, but goes beyond that - it's about people, methodology, psychology, drive, management, projects, career progress and development, etcetera. Self-reflection and his own experiences are probably the main sources of the blog’s essays.

Behind the "Rands" pseudonym goes the name Michael Lopp, possibly best known career-wise as a “Senior Software Engineering Manager” at Apple, although last year (after eight years at Apple) he changed jobs and now works at Palantir Technologies, a company that Does Stuff™ with government statistics.

Many developers may recognize themselves or aspects of their lives in Rands' articles. Case in point, I read one of his more famous articles on N.A.D.D. (Nerd Attention Deficiency Disorder), and instantly recognized a guy I worked with in it - said guy claimed to watch a TV show, read and post on the internets and chat with three people all at the same time. I can do all that too, but have to admit I wouldn't be able to follow the TV show afterwards. This is one of the many (possibly) self-reflective articles he wrote, and describes a nerd's ability and craving to process many information streams at once.

Managing Humans Cover

 

He also writes books, in part based on (and possibly sometimes straight copy & pastes) from his blog-essays. His first book, published in 2007, is titled “Managing Humans” and is basically a collection of essays he wrote over the years on his blog on “handling conflict, managing wildly differing personality types, infusing innovation into insane product schedules, and figuring out how to build lasting and useful engineering culture.” The title of the first chapter already sets the overall tone of the book and Rands' writings overall: “Don't be a prick”.

 

 

Being Geek Cover

His second book is about (and is titled) “Being Geek”, and is advertised as “A career handbook for software developers”. With subjects like giving presentations in chapters named “How Not to Throw Up” and dealing with work-related people with hidden agendas in ”Managing Werewolves”, “Being Geek” is a book on a software developer's career, ranging from the first steps in one’s career to reaching the top, providing various advices and personal experiences in that area.

The title of the book may refer to his “The Nerd Handbook” post , which is a convenient guide for both “nerds” and people that deal with them (both professionally and personally), or why they (in the stereotypical case) hide themselves in their mother's basements (or a modern equivalent thereof). Another good paragraph of that particular essay is about the “annoyingly efficient relevancy engine” nerds possess, which may explain (in part) why some are somewhat socially awkward or just look confused when you try to talk to them.

I should probably just let you read the articles. Read 'em, follow the links to other articles in 'em, or just read the archive. Go on. I'll wait.