markhneedham/blog huggingface dataset:
Selenium - Selecting the original window
Date: 2008-10-25 01:55:18

I've not used http://selenium.openqa.org/[Selenium] much in my time - all of my previous projects have been client side applications or service layers - but I've spent a bit of time getting acquainted with it this week.

While activating some acceptance tests this week I noticed quite a strange error happening if the tests ran in a certain order:

[source,text]
----

com.thoughtworks.selenium.SeleniumException: ERROR: Current window or frame is closed!
at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:73)
at com.thoughtworks.selenium.HttpCommandProcessor.getString(HttpCommandProcessor.java:154)
at com.thoughtworks.selenium.HttpCommandProcessor.getBoolean(HttpCommandProcessor.java:227)
at com.thoughtworks.selenium.DefaultSelenium.isElementPresent(DefaultSelenium.java:394)
----

I tried commenting out some of the tests and then running the other ones and everything worked fine but when I ran all of them the problem returned.

Eventually after some eagle eyed debugging by a colleague of mine we realised that the only difference was the lack of the following line in the failing test:

[source,java]
----

selenium.selectWindow(null);
----

A quick look at the http://release.openqa.org/selenium-remote-control/0.9.2/doc/java/[documentation] explains precisely why this works:

____
if windowID is null, (or the string "null") then it is assumed the user is referring to the original window instantiated by the browser).
____

What had in fact happened was that the previous test had launched a pop up window and when it closed that window the focus wouldn't return to the original window launched when Selenium first started unless we executed the above method call.
Don't shave the yak, ask 'Why are we doing this?'
Date: 2008-10-25 01:34:53

One of the very common pitfalls I make when working on things is to get so engrossed in the technical details of the problem that I completely forget the reason for doing it in the first place.

Over the last week or so I have noticed myself trying to solve some ridiculous problems without considering whether I am solving the right problem in the first place.

To give an example, I was working with Hibernate earlier in the week trying to setup a new mapping between two entities which involved creating a composite key on one of the entities, which led to us having to work out how to do that on the database, then editing our migration script, then trawling Google to work out why our mapping wasn't working, before a colleague overheard our pain and pointed out that we had over complicated matters.

This is commonly known as http://sethgodin.typepad.com/seths_blog/2005/03/dont_shave_that.html[yak shaving]. I've read several examples of this but the basic premise is that you start out intending to do one thing, realise that you need to do something else to achieve this, then something else to do that, and so on until you're so far away from the original problem that you forget what it actually was.

A http://lizdouglass.wordpress.com/[colleague] of mine has been using a quite simple yet effective way of helping us to stop doing this so frequently - they simply ask '*why are we doing this*' before we start doing anything and then when we seem to be going down a path that is leading nowhere.

From what I understand, this is fairly similar to http://en.wikipedia.org/wiki/5_Whys[Toyota Production System's 5 Why approach] to problem solving although I imagine it is probably a little less annoying!

I tend to use the somewhat rough guideline that if something seems overly difficult to do then we are probably doing it wrong much the same way that if something is very difficult to test then the design probably needs looking at.

In summary, take a step back, consider what it is you're trying to do, and *don't shave the yak*!
Null checks everywhere and airport security
Date: 2008-07-18 08:32:00

Having just flown half way across the world from Sydney to London I've been thinking about how airport security is done and noticed a somewhat interesting link to the use of null checks in code.

In Sydney and Dubai airports my baggage and I were scanned only once  before I was able to get onto the plane. I wasn't scanned again when I went to the departure gate nor when I got onto the aircraft.

Yet I often see code which has null checks peppered all over the place - in fact in some code I've seen there were null checks before every single call on an object. Not only does it make the code look extremely ugly, but a lot of the checks were completely pointless since there was no chance of the object being null anyway.

Imagine how annoyed we would be if they checked our baggage at every single step from entering the airport to getting on the plane! So let's cut out unnecessary null checks!
Do IDEs encourage bad code?
Date: 2008-07-27 11:43:30

Although modern day IDEs (Eclipse, IntelliJ, Resharper etc) undoubtedly provide a lot of benefits when writing code, I am starting to wonder if the ease at which they make things possible actually encourages bad habits.

Useful features such as creating and initialising member variables from the definition of a constructor are quickly nullified by the ease at which one is able to create getters/setters/properties for these same member variables. All hopes of encapsulation gone with a few clicks of the mouse.

The counter argument is that you need to work responsibly when given a powerful tool, but it just seems to me that it's hard enough to write good OO code (too hard maybe?) - anything which makes it harder is not a good thing!

I am convinced that IDEs need to provide an Office paper clip style Martin Fowler which pops up whenever you do something questionable (such as creating getters for every field on a class) and asks whether you really want to do what you're doing.

Or maybe there is too much cranking out of the code and not enough thinking about the design of what we're coding that's the real problem...
BDD style unit test names
Date: 2008-09-04 00:05:18

A http://www.fuzzylizard.com/archives/2008/09/03/977/[couple] http://sarahtaraporewalla.blogspot.com/2008/08/test-names-go-wild.html[of] my colleagues have been posting about how to name your unit tests based on this http://blog.jayfields.com/2008/05/testing-value-of-test-names.html[original post] by Jay Fields.

I think that test names are useful, especially when written in a http://dannorth.net/introducing-bdd[BDD] style expressing what a test is supposed to be doing.

For example, in a C# NUnit test we might see the following as a test name:

[source,csharp]
----

[Test]
public void ShouldDoSomething()
{
	// Code testing that we're doing something
}
----

I write all my tests like this and I'm often asked what the point of the 'Should' is, why not just name it 'DoSomething'.

For me although it's a subtle change it influences the way that people look at the test. They can look at the test in a much more critical way.

In the above example someone can look at the test name 'ShouldDoSomething' and then think 'Actually no, it should be doing something else.' The test name and the test contents can then be changed to fit this new understanding of the test.

I'm with http://www.fuzzylizard.com/archives/2008/09/03/977/[Chris Johnston] who says the following when it comes to naming tests:

____
One habit that I picked up on my last project was naming a test after I had written it. While creating the unit test, I would simply name it foo(). Then, once I saw what the code was actually doing, I would go back and rename the test to something appropriate.
____

Ideally I want to name the test properly before I write it but sometimes it becomes clear to me exactly what the name should be as I'm writing the test.

If I'm in this situation I usually just name the test 'ShouldDoSomething' and then by the time I've written it I know what it should actually be doing and I can go back and rename it.

In terms of the general argument over whether we should even have test names, I have only really coded tests in Java and C# so I'm not in a position to comment on whether using a language like Ruby means that they aren't necessary.

For me the test name provides the intention of what you are trying to do, and I like to skim the list of tests in a class - by using Ctrl - F12 and then typing in 'Should' to filter the method list in http://www.jetbrains.com/resharper/documentation/ReSharper25DefaultKeymap.pdf[Resharper] - so that I can see at a high level what is supposed to be happening in that test fixture.

In the world of http://www.jetbrains.com/idea/[IntelliJ] there is also a nice plugin called http://testdox.codehaus.org/[TestDox] which allows you to get a list of your tests nicely indented with spaces.
Configurable Builds: Overriding properties
Date: 2008-09-02 14:49:02

Sometimes when configuring our build for flexibility we don't need to spend the time required to create http://www.markhneedham.com/blog/2008/09/02/configurable-builds-one-configuration-file-per-user/[one build configuration per user] or http://www.markhneedham.com/blog/2008/09/02/configurable-builds-one-configuration-file-per-environment/[one build configuration per environment].

In these cases we can just override properties when we call Nant from the command line.

One recent example where I made use of this was where we had one configuration file with properties in but wanted to override a couple of them when we ran the continuous integration build.

Since build properties are immutable (i.e. once they are set they can't be changed) if we set them from the command line the build script makes use of these values.

For example we might have the following in our build file:

[source,text]
----

<property name="repository.url" value="http://localhost:3000" />
----

But when we're running it on cruise control we have the repository on a different machine. We can override it like so:

[source,text]
----

nant -buildfile:build-file.build target-name -D:repository.url=http://some-remote-url
----

If we have more than one property we want to override it might be a bit annoying to have to pass them all via the command line. We can define them in a file to overcome this problem:

[source,text]
----

nant -buildfile:build-file.build target-name @ci.properties.xml
----

where ci.properties.xml contains the following:

[source,text]
----

-D:repository.url=http://remote-url:3000
-D:some.other.property=newvalue
----

If you start seeing a lot of properties in this file then it is probably an indicator that you need to have a more robust solution but this works for providing simple flexibility.
Configurable Builds: One configuration file per user
Date: 2008-09-02 13:53:53

Following on from http://www.markhneedham.com/blog/2008/09/02/configurable-builds-one-configuration-file-per-environment/[my first post] about making builds configurable, the second way of doing this that I have seen is to have one configuration build file per user.

This approach is more useful where there are different configurations needed on each developer machine. For example, if the databases being used for development are on a remote server then each developer machine would be assigned a database with a different name.

The setup is fairly similar to configuring by environment - the main difference is that we don't have to pass the user in as a parameter. The following would go near the top of the build file:

[source,text]
----

<property name="user" value="${environment::get-user-name()}" />
<include buildfile="${trunk.dir}\config\${user}.properties.xml" />
----

We can then have different configurations for two developer machines like so:

developer1.properties.xml

[source,xml]
----

<?xml version="1.0" ?>
<properties>
	<property name="property1" value="onevalue" />
</properties>
----

developer2.properties.xml

[source,xml]
----

<?xml version="1.0" ?>
<properties>
	<property name="property1" value="anothervalue" />
</properties>
----

We can then run the build file like this:

[source,text]
----

nant -buildfile:build-file.build target-name
----

The disadvantage of this approach is that every time a new developer joins the team they need to create a new configuration file with their settings in. We also need to ensure that the continuous integration build is running using an independent user account. It provides more flexibility and is easier to setup on the plus side.

My colleague http://jimbarritt.com/non-random/[Jim Barritt] points out a similar technique his team is using http://www.markhneedham.com/blog/2008/09/02/configurable-builds-one-configuration-file-per-environment/#comment-161[here].
Configurable Builds: One configuration file per environment
Date: 2008-09-02 01:50:02

One of the most important things when coding build files is to try and make them as configurable as possible.

At the very least on an agile project there will be a need for two different configurations - one for developer machines and one for http://www.martinfowler.com/articles/continuousIntegration.html[continuous integration].

On my last two .NET projects we have setup our http://nant.sourceforge.net/[Nant] build to take in a parameter which indicates which build configuration should be used. We then have a configuration file by that name which contains the environment specific data.

The build file would contain the following code before anything else:

[source,xml]
----

<fail unless="${property::exists('environment')}" message="You must provide the environment property to the build script using -D:environment=[dev|ci]" />
<include buildfile="${trunk.dir}\config\${environment}.properties.xml" />
----

dev.properties.xml would look like this:

[source,xml]
----

<?xml version="1.0" ?>
<properties>
	<property name="property1" value="value1" />
	<property name="property2" value="value2" />
</properties>
----

We would call the build file for the dev environment like so:

[source,text]
----

nant -buildfile:build-file.build target-name -D:environment=dev
----

Configuring the build this way assumes that the dev builds all have the same properties. On the projects where I used this approach this was the case.

The disadvantage of it is that you need to remember to pass in the environment variable each time you call the build. This can be countered by wrapping the full nant call in a batch script if it becomes too much of a hassle.
Connecting to LDAP server using OpenDS in Java
Date: 2008-09-29 23:27:37

A colleague and I have spent the past couple of days spiking solutions for connecting to LDAP servers from Ruby.

We decided that the easiest way to do this is by using https://opends.dev.java.net/[OpenDS], an open source directory service based on LDAP.

One option we came up with for doing this was to make use of the Java libraries for connecting to the LDAP server and then calling through to these from our Ruby code using the http://rjb.rubyforge.org/[Ruby Java Bridge].

This post is not about Ruby, but about how we did it in Java to check that the idea was actually feasible.

The interfaces and classes we need to use to do this are not very http://domaindrivendesign.org/discussion/messageboardarchive/IntentionRevealingInterfaces.html[obvious] so it was a little bit fiddly getting it to work. The following code seems to do the trick though:

[source,java]
----

import org.opends.server.admin.client.ldap.JNDIDirContextAdaptor;

import javax.naming.directory.DirContext;
import javax.naming.NamingException;
import javax.naming.Context;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.InitialLdapContext;

import com.sun.jndi.ldap.LdapCtx;

import java.util.Hashtable;

public class OpenDs {

    public static void main(String[] args) throws NamingException {
        DirContext dirContext = createLdapContext();
        JNDIDirContextAdaptor adaptor =  JNDIDirContextAdaptor.adapt(dirContext);

        // do other stuff with the adaptor
    }

    private static DirContext createLdapContext() throws NamingException {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://localhost:389");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "cn=Directory Manager");
        env.put(Context.SECURITY_CREDENTIALS, "password");

        return new InitialLdapContext(env, null);
    }
}
----

Some points about the code:

* Port 389 is the default port for the LDAP server so unless it's in use this is probably the port you need to connect to.
* 'Directory Manager' is the default 'Root User DN' that was setup when we installed OpenDS although there is more information on what this value may need to be on the http://java.sun.com/products/jndi/tutorial/ldap/security/ldap.html[official documentation].
* We originally tried to connect using http://www.opends.org/promoted-builds/1.0.0/javadoc/org/opends/server/admin/client/ldap/JNDIDirContextAdaptor.html[JNDIDirContextAdaptor.simpleBind(\...)] but it didn't seem to work for us so we went with the JNDIDirContextAdaptor.adapt(\...) approach.
Should we always use Domain Model?
Date: 2008-09-19 08:34:35

During the http://www.markhneedham.com/blog/2008/09/14/altnet-uk-conference-20/[discussion] about Domain Driven Design at the http://www.altnetuk.com/[Alt.NET] conference I felt like the idea of the Rich Domain Model was being represented as the only way to design software but I don't feel that this is the case.

As always in software we http://www.virtualschool.edu/mon/SoftwareEngineering/BrooksNoSilverBullet.html[never have a silver bullet] and there are times when Domain Model is not necessarily the best choice, just as there are times when OOP is not necessarily the best choice.

To quote from Martin Fowler's http://martinfowler.com/books.html#eaa[Patterns of Enterprise Application Architecture]

____
It all comes down to the complexity of the behaviour in your system. If you have complicated and everychanging business rules involving validation, calculations, and derivations\...you'll want an object model.
____

== What are the alternatives?

Domain Model is not a silver bullet and Martin suggests two alternatives when a model driven approach may not be the best choice

. http://martinfowler.com/eaaCatalog/transactionScript.html[Transaction Script] - The best thing about this is its simplicity. It is easy to understand as all the logic is in one place and it is a good choice for applications with a small amount of logic.
. http://martinfowler.com/eaaCatalog/tableModule.html[Table Module] - This is a database driven approach with one class per table. If the system you're working on is using a very table-orientated approach to storing data then this approach may be a good choice.

I think in order to make a Domain Model approach work, everyone in the team (including QAs,BAs etc) needs to buy into the idea and you need some people who have experience in using it so that you can use it in a pragmatic way.

While we have some great tools and techniques available to us in the world of software it is important to remember what problem we are trying to solve and pick the appropriate tool for the job.

_Updated_
I've edited the phrasing of this after conversation - I intended to refer to the Rich Domain Model concept used in Domain Driven Design and was presenting alternatives to this rather than to DDD as a whole.
Testing with Joda Time
Date: 2008-09-24 05:11:20

The alternative to dealing with java.util.Date which http://www.markhneedham.com/blog/2008/09/18/using-javautildate-safely/[I wrote about in a previous post] is to make use of the http://joda-time.sourceforge.net[Joda Time] library. I'm led to believe that a lot of the ideas from Joda Time will in fact be in http://jcp.org/en/jsr/detail?id=310[Java 7].

Nevertheless when testing with Joda Time there are times when it would be useful for us to have control over the time our code is using.

== Why would we want to control the time?

There are a couple of situations that come to mind where it may be useful to be able to control the time in a system:

* There is a piece of code which only executes at a certain time of the day. To see if it executes correctly we need to be able to set the system time to be that time.
* Date calculations - we want to do a calculation on a date and verify the result. We therefore need to be able to control the original date.

Given that, there are two approaches which I have seen to allow us to do this:

== Freezing time

Joda includes a DateTimeUtils class which allows us to http://joda-time.sourceforge.net/userguide.html#Change_the_Current_Time[change the current time].

On the projects I've worked on we would typically wrap these calls in a more descriptive class. For example:

[source,java]
----

import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;

public class JodaDateTime {
    public static void freeze(DateTime frozenDateTime) {
        DateTimeUtils.setCurrentMillisFixed(frozenDateTime.getMillis());
    }

    public static void unfreeze() {
        DateTimeUtils.setCurrentMillisSystem();
    }

}
----

This approach works better if DateTime is deeply engrained in the system and it is difficult for us to abstract dates behind another interface.

The benefit of taking this approach is that we can test for dates without having to change any of our code to add in another level of abstraction which leads to further complexity.

== Time Provider

The alternative approach is to have a TimeProvider which we can pass around the system. This would typically be passed into the constructor of any classes which need to make use of time.

For example, we might have the following interface defined:

[source,java]
----

import org.joda.time.DateTime;

public interface TimeProvider {
    public DateTime getCurrentDateTime() ;
}
----

We can then mock out getCurrentDate() to return whatever date we want in our tests.

The advantage of this approach is that it allows more flexibility around the implementation - it could be used to sync system and local machine dates for example - although at a cost of adding extra complexity.

This approach is similar to thehttp://martinfowler.com/eaaCatalog/plugin.html[plugin pattern] Martin Fowler details in http://martinfowler.com/eaaCatalog/[Patterns of Enterprise Application Architecture] in that we use one implementation of TimeProvider in our application and then a different version for testing.

I generally favour this approach if possible although if a quick win is needed then the first approach is fine.