It’s OK not to write unit tests – of course it is

A couple of days ago I stumbled upon this post. Now, I won’t discuss the post itself (which I think is well structured and surely worth a read) but just its title, that states: it’s OK not to write unit tests.

I’ve been working in C# lately: unit testing in a static language is hell. The clutter created by all those interfaces you’re forced to create solely for mocking is enough reason for give testing up… and that’s just the beginning. So yes, if you’re working in C# (and I think it applies to Java too) it is totally OK not to write unit tests: on the contrary, you’ve gotta have a damn good reason to aim for 100% coverage on a C# project. And by damn good I mean the customer is paying for it because, honestly, maintaining those tests is gonna be a huge waste of time, and you better make sure you can bill that time to someone.

Things change big time when talking about a dynamic language, like ruby. Testing in ruby is so easy that it’s a waste not to do it. Tools are also much better than their .NET counterparts (think RSpec). You still have problems, especially during refactoring, but personally I didn’t feel like throwing my test suite away each time I had to break something. If it’s OK not to write unit tests in ruby? That depends on your situation, but surely the cost of testing is much lower.

Because that’s the point, and that’s what it made me think about the title in the first place: testing has a cost and it’s much higher than what the so-called agile mentors often promise… maybe because the “implementation details” – and the deadlines involved – are usually to be fulfilled by someone else. Telling someone that the cost of testing is lower than the cost of problems due to not testing is lying: it varies greatly according to the situation.

So of course it’s OK not to write unit tests. I wonder how we got to the point that somebody has to argument that. I feel like agile has acquired this silver bullet status and we know how much management love those… let’s stop this before bad things happen – the one who has to maintain the next enterprise behemoth with 2k+ tests that break at every gust of wind might be you.

Windsor custom lifestyles

Windsor provides you with a pretty limited array of options when it comes to lifestyles:

  • Singleton: each time you resolve, you get the same instance. This is, for some reason, the default lifestyle
  • Transient: each time you resolve, you get a new instance. This is what I would have wanted as default 🙂
  • PerThread: it pools a singleton for each thread, so you’ll always get the same instance if you call resolve from the same thread.
  • Pooled: the documentation is not very clear about this but from the source code it seems that a pool with a given capacity is created and on each resolve one of the objects from the pool is returned. I didn’t check how which object to return is determined.
  • there’s also an undocumented PerWebRequest lifestyle and I assume it does just what it says on the tin.

Let’s say that, as it was in my case, you need a container behavior a little different than one of these: you want the container to return a different instance based on a parameter used during the type’s activation. Example:

 
IDictionary argumentsOne = new Hashtable();
argumentsOne.Add("entity", apple);
_container.Resolve<IViewModel>(argumentsOne); // a new instance 
IDictionary argumentsTwo = new Hashtable();
argumentsTwo.Add("entity", pear);
_container.Resolve<IViewModel>(argumentsTwo); // another new instance
IDictionary argumentsThree = new Hashtable();
argumentsThree.Add("entity", apple);
_container.Resolve<IViewModel>(argumentsThree); // the same instance as when called with argumentsOne

So, to get this kind of behavior from your container you need to implement your own CustomLifestyle. The easy way to do it is to subclass AbstractLifestyleManager, which provides you with some methods you can override. The interesting ones are:

  • Resolve which gets called when you try to resolve the type
  • Release which gets called when you try to release the type
  • Dispose which works as usual
  • Init, a callback invoked when your CustomLifestyle gets constructed

Obviously, Resolve should return the instance of the type, be it from your cache or from calling base.Resolve, which should get you a new one. Release should delete the right element from the cache so the next time Resolve is called a fresh instance is returned.

Here follows a sample implementation for the above scenario.

 
public class PerEntityLifestyleManager : AbstractLifestyleManager
    {
    private IDictionary<object, object> _instances = new Dictionary<object, object>();
        
    public override object Resolve(Castle.MicroKernel.CreationContext context)
    {           
        object param = context.AdditionalParameters["entity"];
        if (!_instances.Keys.Contains(param))
        {
            _instances.Add(param, base.Resolve(context));
        }
        return _instances[param];
    }

    public override bool Release(object instance)
    {
        if (_instances.Keys.Contains(instance))
        {
            _instances.Remove(instance);
            return true;
        }
        return false;
    }
}

You should then apply your lifestyle to the types you want to be resolved with it as an attribute, like this:

 
[CustomLifestyle(typeof(PerEntityLifestyleManager))]
public class MyClass : IMyInterface
{
   
}

[rant] C# KeyValuePair.Value = (?)

(A couple of years ago I’d be happily coding around the issue at the moment but you know, Ruby makes you a spoiled bastard: my tolerance level for language WTFs has become zero, so I’m here ranting about this)

So I’ve got my nice ICollections and I’m merrily passing them around and binding them to WPF ListBoxes’ ItemSource and stuff and one of the ICollections happens to be an IDictionary. “No worries”, i thought, “It’s still an ICollection so i don’t see the problem” *type type ItemsSource=”{Binding Path=MyDictionary}” type type*. An F5 later this nice RuntimeException pats me on the back:

A TwoWay or OneWayToSource binding cannot work on the read-only property 'Value' of type 'System.Collections.Generic.KeyValuePair`2

Really. You’ve gotta be shitting me. I mean: what happened is that I’m binding the Value property of each element to an editable property and the guys who designed the KeyValuePair class thought it was a good idea to make its Value property readonly. And it’s not over: if you try to inherit KeyValuePair to fix this WTF yourself you’ll find out that the class is Sealed. I am very aware that writing your personal framework class to save yourself some jumping through hoops is generally a Bad Idea but I feel that if I want to I should definitely be allowed to do that.

Is there a vaild reason I don’t know about that justifies this? If so, please let me know!

xUnit and .NET 4.0

Trying to run xUnit tests compiled against the 4.0 framework with the visual tool (xunit.gui.x86) I was welcomed by an error message telling me that the target .dll was compiled a more recent runtime than the one in use. After some googling I was able to find a fix for the console runner (xunit.console.x86), which consists in adding the following config section to the XML configuration file (xunit.console.x86.exe.config):

 
<startup>
    <supportedRuntime version="v4.0.30319" />
</startup>

(your .NET framework version may vary, take a look at your %systemroot%\Microsoft.NET\Framework for more info)

To make the fix work for the GUI runner you can just make a copy the modified console application’s configuration file and rename it as xunit.gui.x86.exe.config

Unit testing and API design

I have encountered the following situation more than once while working on freightrain: suppose you have a feature in mind, like being able to declare regions (which are other viewmodels, constructed dynamically and plugged into the parent viewmodel’s view accordingly) inside your viewmodel just like this:

class MainViewModel < FreightViewModel

  region :list #:viewmodel defaults to :list
  region :detail, :viewmodel => :customer_detail

end

This has been implemented using a couple of dirty tricks and, of course, it’s all properly tested. The thing is that the tests have been written after the implementation, in a completely separated coding session.

Mind that I am not a very big fan of test driven development: more often than not, especially when the customer is neither trained nor willing to acknowledge the extra effort and the improved quality that comes with it, the costs of test first approach outweigh the benefits it generates. In this case, though, things are different: quality is crucial and I am more than happy to spend time making things better.

Still, I wasn’t really comfortable with writing the test before the actual code. I think that’s because I had a very clear design in mind: testing would just have made the code more complicated than it needs to be. On the downside, the tests written for that piece of code look nothing like the kind of tests that you usually get when doing things TDD style.

What I think I learned from the experience is:

  • While TDD generally helps your design, there are some cases where it gets you to a second best. If you are extremely sure that your design idea is sound then you should abandon testing, do some cowboy coding and when after you’re satisfied with results look back and test everything. The obvious trap is to ditch testing indefinitely: don’t do that.
  • Application design is very different from API design and you have to act (and test) accordingly. Testing the how doesn’t feel that wrong at this level.
  • Sometimes it’s easier to solve a problem with an if or two than to rearrange things: it’s a bad idea and you will see it by the time you test. While ifs are tolerable at the application level they’re a real pain when working at a lower level, and the better the surrounding design the more they hurt. Don’t ignore the warnings.

Programmers are a commodity… right?

A month or so ago I noticed a quite odd advertise on the billboard just outside the department I’m working at KTH, going more or less like this:

C++ junior programmer wanted!
SQL, Javascript and Actionscript a plus
Call 0123 for more info

First two things that came to mind were recruiter fail and man, this guys must be really desperate to put an ad here. Now, while the ad isn’t odd in itself, the place where they decided to hang it is certainly not the most suitable at the campus: the department is purely humanistic and there is no chance on earth to find a programmer over there. Well, except me (maybe they know I’m working here! Creepy! :-\ ).
But then I was even more staggered when, after a couple of weeks, it was replaced with the following:

Flash/actionscript programmer wanted!
No working experience required
Call 0123 for more info

It might have meant two things: either they found the guy the wanted and now they’re looking for an additional flash dev or (my bet was on this one) they couldn’t find anybody and they decided to aim lower. I knew I betted on the right horse when yesterday the ad was replaced once more:

Offering internship!
Do you have any experience with HTML/web site building?
Call 0123 if you're interested!

Fellow developers, shouldn’t we all start to charge more?

Custom table name in datamapper

I didn’t know how to do this and it took me a while to find out, so I’m posting it here. Let’s take a look at the following class:

 
class Author

  property :id      , Serial, :key => true
  property :surname , String, :length => 100
  property :initials, String
 
end

And here is the same class, changed to be persisted to a table called my_table_name, of course assuming that the repository in use is default

 
class Author
  
  storage_names[:default] = "my_table_name"
  
  property :id      , Serial, :key => true
  property :surname , String, :length => 100
  property :initials, String
 
end

The storage_names class method is in the class DataMapper::Model, you can find the documentation here. It is also possible to call storage_name= but it doesn’t work… just use storage_name[repository] =

I’m done with the server

I am in Stockholm at the moment, working at KTH, and for the project I am working on I will need to share a database with a department in university of Göteborg, so I thought it would be nice to have that database on a server somewhere. I had pretty much the same need for a different project at the university of Brescia in Italy and, when I actually went asking for resources to the local sysadmins, they told me that the faculty’s DB (oracle) was running on a remotely hosted machine (i.e. the university, an engineering faculty, does NOT have any kind of internally-owned server) and, understandably, there was no way I could get my hands on that. The only feasible option was to hook a standard desktop machine into the local network but, of course, it then would have been accessible only from the university network. That would have been enough for me but, by the moment I asked, there was not a single machine available and, as soon as they get one, they will let me know.
Now back here in Sweden: last week I went to the network support offices to have a talk with the sysadmins about the possibility of having a database share available somewhere on the university servers. I was already prepared to receive a bold ‘no’, since in Italy it took quite some effort just to have a talk with the powers that be and I was going to the KTH support office with no appointment and no professors backing me up, so I was a complete stranger to them. Surprisingly, they actually received me on the spot and so I explained what the situation was, what I needed and why; after the talk they dismissed me with a ‘we’ll let you know’ and I walked out the office with the feeling I was not going to hear from them again.
So, I was quite surprised when, the day after, I found the following in my inbox:

Hi,

I'm done with the server, at the moment you only have a MySQL account on
it, but we can arrange shell access if needed. I've created the
database ****, your account has full access to it.

***.***.kth.se
OS Ubuntu Server 8.04.3 LTS
CPU 2 x Intel Xeon E5310 @ 1,6 GHz
MEM 2048 MB RAM
DISK 15 GB, all on /

It’s a virtual machine all just for me, I have an account with superuser privileges on it and I can access it via SSH.
By the way: I don’t feel like this is should be taken into account when describing what the general situation is like in both Italy and Sweden, as I’m sure there is a wide range of qualities of service in both countries. Anyway, thanks a lot to Felix and the other guys here at the KTH tech support for their excellent work: they’ve surely made my job much easier.

This is my keyboard…

there are many like it but this one ‘s mine. Your keyboard is probably the less expensive piece of hardware in your workstation. If you’ re a programmer and you’ re working with a cheap keyboard it’s because either you’ve never learned how to leverage its potential or you’ve never put your hands on a good one.
If you’re making heavy use of the mouse you should try this little experiment: start your IDE of choice, unplug your mouse and try to get something done. At first it will be impossible even to do the simplest task but, with time and practice, you will feel more and more comfortable. Coding without leaving your hands form the keyboard has a number of benefits you should keep into account:

  • Speed boost – moving the mouse cursor around takes a whole lot of time. Even just getting the habit of accessing the menu bar with Alt+key will make you a lot faster.
  • No loss of momentum – the lone fact that you have to move your main hand back and forth from the keyboard to accomplish the most trivial task makes concentration much more difficult to attain. Keeping both your hands on the keyboard makes everything smooth, to a point that you’re not even explicitly thinking about each single step of the task.
  • It makes you look cool – (to other geeks). But hey, it surely shows that you’ve put some effort into improving your craft. That’s always a good thing.

Now, don’t get me wrong: I’ve got nothing against the mouse as a device. It’s just that i don’t think that coding is one of the activities that require the mouse the most, not at least as much as it is usually employed.
Take for instance first person shooters, as Quake or Unreal: I think they make a great use of the mouse. The problem with programming is that you need both of your hands on the keyboard. If we happened to have another hand free to use for the mouse it would have been a different story but, at the moment, the choice is between switching your hands between the keyboard and the mouse or abandon the mouse.

There are plenty of keyboards around to choose from. What is the best depends only from you and your preferences but I believe there are some attributes every good keyboard should have:

  • Excellent feedback – to keep your writing fluid and without typos it essential that you are able to feel when a key gets pressed and released almost subconsciously. Buckling spring keyboards will give you the best tactile and audible feedback you can get, but they’re really loud. A good compromise is the scissor switch technology, nowadays the default for laptops, which will give you excellent feedback without being so annoying to your coworkers. Most of the keyboard you will find, also the vast majority from the more expensive ones, will have dome switches instead. They really suck and you should better avoid them.
  • Standard layout – having all the keys in the places you expect them to be is crucial, especially after you get used to the layout. It is especially important that the end/home/ins/del keys are in fixed places, since those are the ones you will have to stretch the most to get to. You can get used to non-standard layouts, that’s for sure, but it will be a real pain when you don’t have your keyboard of choice at your disposal, or if you routinely switch between different keyboards (as is the case if you have, for example, a desktop and a laptop).

I recently bought a new laptop and I made the big mistake of not keeping the keyboard into account: it’s a good keyboard, it gives nice feedback, but the non-main keys are scrambled all over the place. I fortunately use a vim-like layout so the damage is minimized, but it’s still annoying.
Aside from my laptop’s keyboard, I currently use two other keyboards:
a Model-M IBM, a gift from a colleague (thanks Mirco!)

and a DasKeyboard.

The first one is just the BEST keyboard I’ve ever tried. A clone of the original is still in production so you can easily get your hands over one of these jewels. The only drawback is that everything else you will use afterwards will seem cheesy and you will take a while to readjust.
The DasKeyboard has also great feedback, looks really slick and the ultimate version gives you a chance to show off how geeky you are 🙂

Horizontal vs. vertical complexity

If i were to choose a principle that summarizes what’s behind a good design, that would absolutely be KISS : as the wise once said nobody is really up to the challenge of being a programmer. Simplicity often means humbleness, which in turn shows that the author has already learned his lesson.
That said, complexity is unavoidable. Code itself is complexity: no lines of code is always the most elegant solution but, zen value put aside, it accomplishes little. We have to deal with some amount of complexity no matter what, so i think it is better to know who your enemy is than to bury your head in the sand ( even if that’s really agile 😉 ).
Let’s take a look at the following snippet :

Now the car must be modified: it shouldn’t be able to move if the engine is not ignited. What should we do to implement this change in behavior?
Horizontal complexity

An if in the right place and voilà, the job is done. It’s the kind of change that TDD (and, by proxy, YAGNI) often brings to: the simplest thing that can possibly work, which is also very often the best thing you can do. It’s horizontal because it doesn’t add layers to your design: an atomic change is most likely to involve just one method or, at most, one class. It’s almost harmless when taken in small quantities but, when misused, can turn really, really bad.
I believe that the real problem about ifs (and conditional statements as a whole) is that they’re too easy. Providing such an easy way to fork the world in two at the language level is like putting RPGs for sale at the grocery store – no matter what’s your level of trust in people’s reasoning, somebody’s gonna get hurt… heck, there’s a whole movement out there trying to put them down.
Vertical complexity

Two new classes and constructor logic: that’s the price you pay so you don’t have to put one of that nasty ifs into your pristine method. It also hides some of the code away from sight: looking at the method only is no longer sufficient to understand its behavior. It’s vertical because the change in your code will be likely to be small in each single part but distributed in various layers.
If you write one if too much you ‘re shooting yourself in the foot; if you do this the wrong way you ‘re blowing your whole leg off.
Overengineering is cheap and often mistaken as quality. The damage done, which often presents itself in the form of Yet Another Crappy Framework destined for internal use, is massive if measures are not taken early so i think it’s a really good idea to stop coding if you don’t know what you’re doing, like when:

  • You just finished reading a certain book which was totally sweet and you can’t wait to see memento in action. On the invoices module.
  • You had a genius idea and you absolutely must put it in your code so everybody knows how freakin’ smart you are.
  • You start to wonder how cool would that be to have all that nasty business logic in a XML file so the customer can edit it himself

In the end…
Which one is better? That depends on you and on the situation: if the code you’re writing will be not be seen by human eyes after it is deployed then i think design and quality are not that important. If you know from the start your code will be mantained (which is pretty much always) it might be a good idea to add some structure (just some) even if the task to accomplish is simple. But if you have no clue please be a good boy, stop coding that CommonMethods class and ask for guidance 🙂