markhneedham/blog huggingface dataset:
Coding Dojo #4: Roman Numerals
Date: 2008-11-30 17:58:27

We ran our 4th coding dojo on Thursday night, attempting to solve the http://sites.google.com/site/tddproblems/all-problems-1/Roman-number-conversion[Roman Numerals problem] from the http://sites.google.com/site/tddproblems/all-problems-1[TDD Problems website].

== The Format

We ran with the http://codingdojo.org/cgi-bin/wiki.pl?RandoriKata[Randori] approach again with between 4-6 participants taking part. We coded for about an hour and a half.

The pair coding were sat at the front of the room this time in an attempt to keep the focus on the code, a problem http://www.markhneedham.com/blog/2008/11/22/coding-dojo-3-krypton-factor/[identified last week].

== What We Learnt

* I had worked on this problem myself a couple of weeks ago but it was interesting to note how many more of the edge cases we managed to cover when working as a group. We had an discussion around *where the validation of what constitutes a valid roman numeral* should go. We ended up validating when the roman numeral object was converted into an integer, the other option being to do constructor validation. I'm not sure exactly when each approach is applicable - I would tend to do constructor validation when data is coming in from the user interface otherwise validating when the object is used.
* Having the pair at sit at the front of the room worked much better in terms of stopping others drawing on the white board and we seemed to achieve *greater focus on the problem* than in the previous weeks although I'm not sure whether or not this is directly linked to the positioning of the coding pair.
* The idea of keeping *minimal state* in the code was an interesting idea that was suggested early on and one which we kept to. I've not considered this as part of my approach to solving problems before but it makes sense in helping to drive simplicity of design.
* The *drive for the green bar* was again in evidence - on one occasion I tried to refactor and make the test pass in one go, forgetting that this would keep us away from the green bar for longer. This was pointed out by my pair and I backtracked the refactoring and just made the bar green.
TDD: If it's hard to test reflect on your approach
Date: 2008-11-30 18:42:29

Chad Myers gets it spot on in his recent post about http://www.lostechies.com/blogs/chad_myers/archive/2008/11/21/do-not-test-private-methods.aspx[not testing private methods] - private methods are private because they should be inaccessible from outside the class and their functionality should be tested via one of the public methods that calls them.

I've found that when a piece of code seems really difficult to test without exposing a private method then we're probably trying to test that functionality from the wrong place.

I came across just this problem earlier this week when trying to test the functionality of one of our controllers - we are using the http://www.asp.net/mvc/[ASP.NET MVC] framework to build our application.

My first approach was to try and test everything from the controller test but it quickly became apparent that this was going to be very difficult as the only data we had access to was the ActionResult which was insufficient for our testing purposes.

It became clear that if we put the logic into one of the objects being created inside the method (by a WCF web services call) that it would be significantly easier to test the logic - so that's what we did! Suddenly it became much easier to test and we were able to come up with other test scenarios that we hadn't previously considered.

The lesson to learn here is to constantly reflect on whether we are testing from the right place and *if it feels too difficult then it probably is*.

Another testing lesson I learnt recently was not to override protected methods in order to test other logic in the class. This is arguably even worse than exposing private methods because now we are not testing the production code but a variant of it.

The reason I did it was because all the logic for preventing caching of data was encapsulated into a single method and since I wasn't interesting in testing that part of the code I thought it would be fine to just ignore it for those tests.

http://pilchardfriendly.wordpress.com/[Nick] pointed out that the actual problem was that we were missing an abstraction and as a result had ended up creating a dependency that made testing difficult. In this case the object was dependent on HttpResponse.

The lesson here is to ensure that objects *depend on abstractions and not on concrete implementations* wherever possible.

The underlying lesson in both cases being that we need to be constantly reflecting and questioning our approach to ensure that we write clean code and test that code in a clean way.
Hamcrest Matchers - Make the error message clear
Date: 2008-11-08 02:46:59

We have been making good use of http://code.google.com/p/hamcrest/[Hamcrest] matchers on my current project for making assertions, and have moved almost entirely away from the more traditional JUnit assertEquals approach.

There are several reasons why I find the Hamcrest matcher approach to be more productive - it's more flexible, more expressive and when an assertion fails we have a much better idea about why it has failed than if we use a JUnit assertion for example.

This applies especially when we get a test failing as part of the build as compared to running a test from the IDE where the source code is close at hand and non descriptive error messages may not be such a problem.

It therefore makes sense when writing custom Hamcrest matchers to ensure that we do indeed provide a clear error message so that it is obvious how to fix the test.

The convention seems to be that we should first state the static method name of the matcher and then in brackets list the expected arguments.

To give an example from a matcher we wrote yesterday:

[source,java]
----

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.TypeSafeMatcher;

public class ContainsAllOf<T> extends TypeSafeMatcher<T> {
    private String[] messages;

    public ContainsAllOf(String... messages) {
        this.messages = messages;
    }

    public void describeTo(Description description) {
        description.appendText("containsAllOf(");
        for (String message : messages) {
            description.appendText(",");
            description.appendValue(message);
        }
        description.appendText(")");
    }

    @Factory
    public static <T> ContainsAllOf containsAllOf(String... messages) {
        return new ContainsAllOf(messages);
    }

    public boolean matchesSafely(T t) {
        return contains(t, messages);
    }

    private boolean contains(T t, String[] messages) {
        boolean containsAllMessages = true;
        for (String message : messages) {
            if (!t.toString().contains(message)) {
                return false;
            }
        }
        return containsAllMessages;
    }

}
----

If we call this in our test with a value that doesn't exist:

[source,java]
----

assertThat("mark's cool message", containsAllOf("mark", "cool", "message", "notThere"));
----

Running the test results in the following error:

[source,text]
----

java.lang.AssertionError:
Expected: containsAllOf(,"mark","cool","message","notThere")
     got: "mark's cool message"
----

We can easily see what the problem is and how to go about fixing it, which I feel is the most important thing when it comes to test assertions.
CSS in Internet Explorer - Some lessons learned
Date: 2008-11-01 01:24:51

I've spent the last few days working with CSS, and in particular trying to make a layout which works perfectly fine in Firefox work properly in Internet Explorer 6.

I'm far from an expert when it comes to this but I've picked up a few lessons from our attempts to get identical layouts in both browsers.

* Internet Explorer seems to do some crazy stuff when it comes to http://www.webcredible.co.uk/user-friendly-resources/css/internet-explorer.shtml[padding and margins] - we were often ending up with huge margins where we hadn't even specified any. A useful approach pointed out by http://www.workingwithrails.com/person/8781-josh-price[Josh] was *resetting the margin and padding for the whole page* so that IE's default padding was removed. Putting the following code in your style sheet will do this: ~~~css * {padding:0;margin:0} ~~~
* Despite the fact that we start with IE and Firefox on an even keel, there were still differences in how they rendered some spacings that we tried to apply. I don't think this is necessarily a good long term fix but it seems that *if you start a property name with an underscore IE will respect it but Firefox will ignore it*. This is known as the http://www.wellstyled.com/css-underscore-hack.html[MSIE underscore hack], which describes it fairly accurately! We can therefore set up IE only CSS properties like this: ~~~css _margin: 0 0 2px 0; ~~~
* One of the other problems we came across was the http://www.positioniseverything.net/explorer/peekaboo.html[hidden text bug] - sometimes when we refreshed the page text inside a floating div would just disappear until you selected it with the mouse when it would reappear. We found a http://www.satzansatz.de/cssd/onhavinglayout.html[couple] of http://plone.org/documentation/how-to/internet-explorer-invisible-text[posts] which explained that the problem was being caused by IE not correctly setting the element size for floating elements on the page. The other posts go into more detail, but the fix that worked for us involved *forcing IE into layout mode* by applying a small height to the element that was being hidden: ~~~css .visualIEFloatFix { height: 0.01%; } ~~~

I'm sure there will be further learnings on my CSS travels - I've been trying to find some resources which describe good patterns to use with CSS but I've only come across a book called http://cssdesignpatterns.com/[Pro CSS and HTML Design Patterns] so far.

Anyone know if this book is any good or if not what a better alternative is?
File system equivalent of commenting code
Date: 2008-11-06 21:51:09

Last week I came across what I have decided is the file system equivalent of commenting out code - not deleting directories when we are no longer using them.

The specific situation we ran into was while trying to make some Tomcat configuration changes but everything we changed was having no effect on what we were seeing on the web site.

Eventually we realised that we were actually changing the configuration in the wrong place - we actually had two Tomcat folder lying around. One for Tomcat 6 and one for Tomcat 5.5. We are running the former but were changing the configuration for the latter by mistake!

Of course the underlying problem was that we weren't paying enough attention to what we were changing, but if there had been only one possible place to make changes then we wouldn't have had a problem.

*Lesson Learned:* Treat the file system like the code - if something is not needed delete it straight away. It can always be retrieved from source control in the future if it's actually needed.
Lambda in C#: Conciseness v Readability
Date: 2008-11-24 23:41:36

One of the things I really disliked when I first came across C# 3.0 code was http://www.davidhayden.com/blog/dave/archive/2006/11/30/LambdaExpressionsExtensionMethodsLINQ.aspx[lambda functions].

At the time I remember speaking to my http://markthomas.info/blog/[Tech Lead] and expressing the opinion that they were making the code harder to understand and were valuing *conciseness over readability*.

After a week of reading about the new C# features and understanding how they worked the code was now more readable to me and a lot of the boiler plate code that I had come to expect was no longer necessary.

My favourite example of the power of lambda is when we want to iterate through a collection of items and apply the same operation to every item in the collection.

In normal C# we might do this:

[source,csharp]
----

public class Foo
{
    private String bar;
    private String baz;

    public Foo(String bar, String baz)
    {
        this.bar = bar;
        this.baz = baz;
    }

    public override string ToString()
    {
        return string.Format("{0} - {1}", bar, baz);
    }

}
----

[source,csharp]
----

var foos = new List<Foo>();
foos.Add(new Foo("bar1", "baz1"));
foos.Add(new Foo("bar2", "baz2"));

var fooString = new List<String>();
foreach (var foo in foos)
{
    fooString.Add(foo.ToString());
}
----

Using the power of C# 3.0 we can change that last for each statement to read something like this:

[source,csharp]
----

var fooString = foos.Select(f => f.ToString());
----

This is much more concise but I think the judgement on its readability depends on one's understanding of the language feature.

One idea I am considering trying is using methods which describe more clearly what the lambda function is doing. This is an idea I came across from Kris Kemper's post about using http://blog.kriskemper.com/2008/10/23/granularity-of-abstractions/[similar Ruby language features].

In the example I gave perhaps wrapping the foo.Select(...) in a method called 'ConvertToStringRepresentation()' might make it more readable - it's clearly up for debate though.

When I was learning how lambda worked I found it useful to be able to do the comparison of how you would write code without it and being able to compare that with how you could do it with lambda. I also found having some understanding of how http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/[Ruby blocks] worked made it easier as well.

Clearly having powerful language features means that a language is much easier to abuse but I think if used sensibly then *readability and conciseness need not be mutually exclusive.*
Testing Test Code
Date: 2008-11-23 23:21:46

One of the interesting discussions that has come up on several projects I've worked on is whether or not we should test code that was written purely to help us test production code.

One of the main arguments used against testing test utility code is that it is not production code and therefore perhaps doesn't need to be held to the same standards because it lacks the complexity of production code.

Even ignoring this assumption, which I don't agree with, I think we are still missing the point as to why we actually test in the first place.

Although a lot of the value of the test driven approach is that it helps us to http://www.markhneedham.com/blog/2008/10/01/tdd-without-the-design/[drive design], the other side of the story, which we perhaps only fully appreciate after working with legacy code, is the safety net that having a suite of tests around our code provides.

From my experience the *complexity of the test utility code is what determines whether it is valuable to test* it or not. If it's just builders to help create test data then I would agree there is little value in testing it, but if there's actual logic and/or complexity then having a safety net is a good thing. Even if the tests are very simple they help protect us to ensure our code is still working when we make future changes.

The thing to watch for is that test utility code often starts off being very simple but slowly complexity creeps in making it more difficult to verify whether it actually does what we want it to.

As a rough marker, when you end up debugging through your test utility code to work out why it isn't working as you expected it's probably time to consider putting some tests around it.
Build: Red/Green for local build
Date: 2008-11-15 08:26:21

One thing I'm learning from reading http://www.amazon.co.uk/Toyota-Way-Management-Principles-Manufacturer/dp/0071392319/ref=sr_1_1?ie=UTF8&s=books&qid=1226698369&sr=8-1[The Toyota Way] is that visual indicators are a very important part of the Toyota Production System, and certainly my experience working in agile software development is that the same is true there.

We have certainly learnt this lesson with regards to http://martinfowler.com/articles/continuousIntegration.html[continuous integration] - the build is either red or green and it's a very obvious visual indicator of the code base at any moment in time.

On my last two projects we have setup build lights which project the build status even more visually without us even having to go to the reporting page.

I have never thought about applying this principle when running the build locally but my colleague http://jamescrisp.org/[James Crisp] has setup our build to light up the whole background of the command prompt window red or green depending on the status code we get back from running http://nant.sourceforge.net/[Nant].

James has promised to post the code we used from the command prompt to do this on his blog - I've tried to work out how to achieve the same effect in the Unix shell but I haven't figured out how to do it yet. I've worked out how to set the http://linuxshellaccount.blogspot.com/2008/03/using-color-in-linux-or-unix-shell.html[background colour for the prompt] but not for the whole window - if anyone knows how to do it, let me know!

The idea is fairly simple though:

* Run the build
* If the exit status is 1, make the background red
* If the exit status is 0, make the background green
Agile: The Client/User dilemma
Date: 2008-11-12 07:22:55

While reading Marc's post about the http://www.dancingmango.com/blog/2008/11/10/customer-or-client/[Customer or Client] naming dilemma I was reminded of another situation I have noticed in software development - the Client/User dilemma.

From my experience of agile projects it tends to be much more likely that we can get easy access to our client than to the users of the system we are writing.

Alistair Cockburn mentions in http://www.markhneedham.com/blog/2008/11/05/crystal-clear-book-review/[Crystal Clear] that having an expert user sit with the team can be very useful, but it is not something that I have experienced on all the projects that I have worked on.

I think the problem is that it is very difficult to get access to these people. All of the projects I have worked on have been internal systems, and it can be difficult to get access to the users because they are very busy doing their day job and don't have the time to spend talking about what they want in the system.

We therefore either end up with the client conveying their wishes by taking a best guess or engaging some users and working out what they want.

Sometimes the client is a former user of the system in which case their guess is likely to be fairly accurate and we don't have a problem.

The problem I have noticed is that sometimes the client can come up with requirements which don't seem aligned with what the user would actually want.

In these situations it is very difficult to know what to do because on the one hand the client is the one paying for the system and therefore you need to keep them happy but on the other hand the success or failure of the project will probably rest on the users' reaction to the system.

I'm not sure what the best solution is for these situations, it would be interesting to hear others' opinions on this.
Agile: A reminder of the benefits of colocation 
Date: 2008-11-22 12:46:27

Sometimes it's the seemingly small details of the agile/XP approach to software development that make it so much more effective than the traditional approach.

I was reminded of this last week with regards to having http://agilesoftwaredevelopment.com/blog/cspag/case-collocation[co-located teams] with the developers, BAs, QAs and the business people all sitting in close proximity.

I was working on the auto completion function for one of our screens and the QA on the team, who was sitting next to me, asked me if I could look through the acceptance criteria that he was working on.

This conversation was almost perfectly on cue because I was just about at the point where I had covered all the happy path cases and needed to understand the other paths. While looking through the acceptance criteria we needed some clarification with regards to exactly what the business wanted.

We went over to where the BAs were sitting and posed the question. Luckily they had just had the conversation with the business people and were able to explain the intent behind the criteria.

Interestingly writing this has made me realise that there are a couple of points in our process where more communication would make things flow more smoothly but seeing the speed with which we were able to go from confusion over a requirement to complete understanding was a really great reminder for me.
Coding Dojo #3: Krypton Factor
Date: 2008-11-22 11:00:03

We ran our 3rd coding dojo on Thursday night, attempting to solve the http://icpcres.ecs.baylor.edu/onlinejudge/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=65[Krypton Factor] problem from the Online Judge website.

== The Format

We ran with the http://codingdojo.org/cgi-bin/wiki.pl?RandoriKata[Randori] approach again, exactly the same as http://www.markhneedham.com/blog/2008/11/13/coding-dojo-2-bowling-game-object-calisthenics-continued/[last week] but this time we only had 4 participants for the majority of the coding session.

== What We Learnt

* We still ended up spending a *large percentage of the time drawing out the problem on the whiteboard and not coding*. This seemed partly due to the difficulty of the problem and partly due to the layout of the room whereby the pair coding were sitting at the back and the people watching were sitting in front of them. We are going to try changing the layout so the *pair at the computer are at the front of the room* to shift the focus to the code.
* The problem we picked was very algorithmic in nature and we spent a lot of time discussing how to write an optimal solution to it rather than getting a naive one working first. It was eerily similar to the situation we sometimes end up with on projects where we are *prematurely optimising* a system before we actually have it working.
* The previous two coding dojos we had focused on a problem which was easier to understand and perhaps more suited to a TDD and Object Oriented approach. We are probably going to try and focus more on problems which we can understand more quickly therefore allowing us to focus more on the way that we solve them.
* One thing I learned personally when pairing with http://fragmental.tw/[Phil] was the *need for clear naming* of classes and methods. We had let this slip a bit as we struggled to progress with the problem to the point where the naming we had didn't really make any sense. When Phil came to the keyboard he pointed this out and we refactored the code until it made more sense.
* A common trend across the three coding dojos we have run so far is that we are always working with a very high level problem and struggle to break it down into smaller chunks that we could work on. It was suggested that perhaps *breaking down the problem into stories* might be more effective since this is what we are used to from our project work. We have often ended up with classes have a lot more than one responsibility due to our attempts to solve the problem from the first acceptance test that we write. Writing stories would help in our attempts to take *baby steps* on the way to solving the problem.