markhneedham/blog huggingface dataset:
jQuery: Dynamically updating a drop down list
Date: 2010-06-30 10:46:20

We recently had a requirement to dynamically update a drop down list based on how the user had filled in other parts of the page.

Our initial approach was to populate the drop down with all potential options on page load and then add CSS selectors to the options that we wanted to hide. That worked fine in Chrome and Firefox but Internet Explorer seems to ignore CSS selectors inside a drop down list so none of the options were being hidden.

We therefore had to try and dynamically add and remove options from the drop down list instead.

The list that we initially loaded onto the page was like this:

[source,html]
----

<select id="foo" name="foo">
<option value="A" selected="selected">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="Not applicable">Not applicable</option>
</select>
----

http://twitter.com/christianralph[Christian] eventually came up with the following solution to hide/show those options and select the appropriate one after several hours of trial and error:

[source,javascript]
----

// captured on page load
var originalFooOptions = $("#foo > option");
----

[source,javascript]
----

var foo = $("#foo");
var dependentField = $("#fieldFooIsDependentOn");

if(notApplicable()) {
	foo.children("option[value!='Not applicable']").remove();
	foo.val("Not applicable");
} else {
	foo.empty();
	$(originalFooOptions).each(function() {
		var newOption = $(this).clone();
		if ($(this).val() === dependentField.val()) {
			newOption.attr("selected", "selected");
		}
		newOption.appendTo(foo);
	});	
}
----

Another approach we tried was to try and dynamically update 'foo' rather than removing all the items and then adding them back.

Unfortunately we kept getting an 'unspecified error' on Internet Explorer 6 when we tried to set the selected value with that approach.
Fluent NHibernate: Seeing the mapping files generated
Date: 2010-06-15 23:15:30

We've been fiddling around with http://fluentnhibernate.org/[Fluent NHibernate] a bit over the last couple of days and one of the things that we wanted to do was output the NHibernate mapping files being generated so we could see if they were as expected.

I couldn't figure out how to do it but thanks to the help of http://twitter.com/jagregory/status/16210304123[James Gregory], http://twitter.com/trullock/status/16214631489[Andrew Bullock] and http://twitter.com/MatthewErbs/status/16213970597[Matthew Erbs] on twitter this is the code that you need in order to do that:

[source,csharp]
----

Fluently
.Configure()
.Database(MsSqlConfiguration.MsSql2000.ConnectionString("connection string"))
.Mappings(m => m.FluentMappings.ExportTo("c:\\directory-to-output-files-to"))
.BuildSessionFactory();
----

The 4th line is the important one here and we can choose which directory the mappings files get outputted to and then check that everything is getting setup as we'd expect.
C#: A failed attempt at F#-ish pattern matching
Date: 2010-06-13 22:35:14

A few weeks ago we had some http://www.markhneedham.com/blog/2010/04/20/functional-c-an-imperative-to-declarative-example/[C# code around calcuations] which had got a bit too imperative in nature.

The code looked roughly like this:

[source,csharp]
----

public class ACalculator
{
	public double CalculateFrom(UserData userData)
	{
		if(userData.Factor1 == Factor1.Option1)
		{
			return 1.0;
		}

		if(userData.Factor2 == Factor2.Option3)
		{
			return 2.0;
		}

		if(userData.Factor3 == Factor3.Option2)
		{
			return 3.0
		}
		return 0.0;
	}
}
----

I think there should be a more object oriented way to write this code whereby we push some of the logic onto the 'UserData' object but it struck me that it reads a little bit like http://www.markhneedham.com/blog/2010/01/12/f-refactoring-to-pattern-matching/[pattern matching code you might see in F#].

I decided to drive the code to use a dictionary which would store functions representing each of the conditions in the if statements:

[source,csharp]
----

public class ACalculator
{
	private Dictionary<Func<UserData, bool>, double> calculations;
	
	public ACalculator()
	{
    		calculations = new Dictionary<Func<UserData,bool>,double>
                       {
                           {u => u.Factor1 == Factor1.Option1, 1.0},
                           {u => u.Factor2 == Factor2.Option3, 2.0},
                           {u => u.Factor3 == Factor3.Option2, 3.0}
                       };	
	}	

	public double CalculateFrom(UserData userData)
	{
    		var calculation = calculations.Keys.FirstOrDefault(calc => calc(userData));
    		if(calculation != null)
    		{
        		return calculations[calculation];
    		}

    		return 0.0;
	}
}
----

It's less readable than it was before and it's not obvious that the adding of the functions to the dictionary needs to be in that order in order for it to work.

I've simplified the real example a bit to show the idea but I don't think it works as the best abstraction in this situation either way although it was an interesting experiment.
The Refactoring Dilemma
Date: 2010-06-13 13:37:39

On several of the projects that I've worked on over the last couple of years we've seen the following situation evolve:

* The team starts coding the application.
* At some stage there is a breakthrough in understanding and a chance to really improve the code.
* However the deadline is tight and we wouldn't see a return within the time left if we refactored the code now
* The team keeps on going with the old approach
* The project ends up going on for longer than the original deadline
* It's now much more work to move towards the new solution

In the situations I describe the refactorings could have been done incrementally but doing that would take longer than continuing with the original approach and also http://www.markhneedham.com/blog/2010/05/05/consistency-in-the-code-base-and-incremental-refactoring/[leave the code in an inconsistent state].

I think the reason this situation evolves consistently in this manner is because *although we talk about writing maintainable code, delivery is often considered more important*. Pushing out a delivery date in order to refactor code so that it will be easier to work with in the future isn't something that I've seen happen.

Pushing a delivery date out is a cost that we can see straight away.

On the other hand it's quite difficult to estimate how much of a gain you'll get by refactoring to a more maintainable/easier to test solution and that gain will not be immediate.

We therefore end up in the situation where we tend to make major refactorings only if we're going to see a benefit from doing that refactoring before the project ends.

In one sense that seems reasonable because we're trying to ensure that we're adding as much value as possible while the client is paying for our time.

On the other hand we're making life harder for future maintainers of the code base which may in fact be us!

I'd be keen to hear how others handle these types of situations because it feels like this trade off is quite a common one and the way we've dealt with it doesn't seem optimal.
TDD: Driving from the assertion up
Date: 2010-06-14 22:46:00

About a year ago I wrote a post about http://www.markhneedham.com/blog/2009/06/20/book-club-the-readability-of-tests-growing-object-oriented-software-steve-freemannat-pryce/[a book club we ran in Sydney covering 'The readability of tests'] from Steve Freeman and Nat Pryce's book in which they suggest that their preferred way of writing tests is to drive them from the assertion up:

____
Write Tests Backwards Although we stick to a canonical format for test code, we don't necessarily write tests from top to bottom. What we often do is: write the test name, which helps us decide what we want to achieve; write the call to the target code, which is the entry point for the feature; write the expectations and assertions, so we know what effects the feature should have; and, write the setup and teardown to define the context for the test. Of course, there may be some blurring of these steps to help the compiler, but this sequence reflects how we tend to think through a new unit test. Then we run it and watch it fail.
____

At the time I wasn't necessarily convinced that this was the best way to drive but we came across an interesting example today where that approach might have been beneficial.

The test in question was an integration test and we were following the approach of http://www.markhneedham.com/blog/2008/10/30/testing-hibernate-mappings-setting-up-test-data/[saving the test object directly through the NHibernate session] and then loading it again through a repository.

We started the test from the setup of the data and decided to get the mappings and table setup in order to successfully persist the test object first. We didn't write the assertion or repository call in the test initially.

Having got that all working correctly we got back to our test and wrote the rest of it only to realise as we drove out the repository code that we actually needed to create a new object which would be a composition of several objects including our original test object.

We wanted to retrieve a 'Foo' by providing a key and a date - we would retrieve different values depending on the values we provided for those parameters.

This is roughly what the new object looked like:

[source,csharp]
----

public class FooRecord
{
   public Foo Foo { get; set; }
   public FooKey FooKey { get; set; }
   public DateTime OnDate { get; set; }
}
----

'FooRecord' would need to be saved to the session although we would still retrieve 'Foo' from the repository having queried the database for the appropriate one.

[source,csharp]
----

public class FooRepository
{
   public Foo Find(Date onDate, FooKey fooKey)
   {
      // code to query NHibernate which retrieves FooRecords
      // and then filters those to find the one we want
   }
}
----

We wouldn't necessarily have discovered this more quickly if we'd driven from the assertion because we'd still have had to start driving the implementation with an incomplete test to avoid any re-work.

I think it would have been more likely that we'd have seen the problem though.
C#: StackTrace
Date: 2010-06-22 22:27:58

http://twitter.com/dermotkilroy[Dermot] and I were doing a bit of work on a mini testing DSL that we've been writing to try and make some of our interaction tests a bit more explicit and one of the things that we wanted to do was find out which method was being called on one of our collaborators.

We have a stub collaborator which gets injected into our system under test. It looks roughly like this:

[source,csharp]
----

public class StubCollaborator : IGotForcedToCollaborate
{
	public double Method1()
	{
		return CannedValue();
	}

	public double Method2()
	{
		return CannedValue();
	}

	private double CannedValue()
	{
		return 10;
	}

}
----

We wanted to try and capture which of the methods on that object had been called by our system under test and then assert on that value from our test.

While trying to work out how to do this we came across the 'StackTrace' object. We use it like so to work out which public method on that object has been called:

[source,csharp]
----

public class StubCollaborator : IGotForcedToCollaborate
{
	private MethodBase methodCalled;

	..
	
	private double CannedValue()
	{
		methodCalled =  new StackTrace().GetFrames()
                			.Select(f =>f.GetMethod())
                			.Where(m => m.DeclaringType.Name == GetType().Name)
                			.Where(m => m.IsPublic)
                			.First()
		return 10;
	}

	public string GetMethodCalled()
	{
		return methodBase.Name;
	}	

}
----

We needed to only find the public methods because 'CannedValue' was showing up on the stack trace and since it's private this was an easy way to exclude it.

I'm sure there are other ways to get this type of information but we were able to solve our problem really quickly with this solution.
Mercurial: Only pushing some local changes
Date: 2010-06-25 23:32:36

One problem we've come across a few times over the last couple of months while using Mercurial is the situation where we want to quickly commit a local change without committing other local changes that we've made.

The example we came across today was where we wanted to make a change to the build file as we'd made a mistake in the target that runs on our continuous integration server and hadn't noticed for a while during which time we'd accumulated other local changes.

The following is a rough diagram of the situation we had:

image::{{<siteurl>}}/uploads/2010/06/mercurial1.jpg[mercurial.jpg,441]

We had multiple file changes in our working directory which hadn't yet been checked in to the local repository or the central repository.

We wanted to push just the change in blue.

My initial thought was that I could check in just that one file into our local repository and then push it to the central one.

[source,text]
----

hg ci -m "mark: updating build file to fix build" -A /path/to/build.file
----

I then wanted to push that change but when I went to do so I realised that they were other incoming changes which we hadn't yet integrated with.

In order to integrate with those changes we need to make sure that we don't have any locally uncommitted changes which of course in this scenario we do since we deliberately chose not to check in some of our local changes.

One way around this would be to just force the push and ignore the need to integrate with the remote changes but that doesn't seem the right approach to me but I'm not sure what is.

We ended up just checking in everything we had locally, commenting out the bits that we were currently working on, merging with the remote changes and then pushing everything to the remote repository.

That's obviously a really poor way of solving the problem so I'd be interested in what a good way to solve this problem would be!
India Cultural Differences: Stretched work day
Date: 2010-12-20 21:23:39

A couple of months ago I briefly touched on http://www.markhneedham.com/blog/2010/10/17/distributed-agile-cultural-differencesexpectation-disconnect/[the very stretched days I've experienced while working in India].

This is in contrast to what I've experienced in the UK and Australia where the day was much more time boxed and tended to go from 9am to 6pm.

At the moment we also have a call with colleagues in Chicago at 9pm for about 30-45 minutes so the day has now stretched out until nearly 10pm. We start with our standup at 10am.

We're certainly not working all of that time but you're never really done for the day until the call has finished.

With or without the call I've found it a much more difficult environment to work in than anything I've experienced before.

I frequently get to the end of the day and can't really determine whether I've actually achieved anything because I've started and stopping working so many times.

I find I get distracted really easily working in our Pune office so I need my pair to be quite vocal about keeping focus!

One disadvantage of the stretched work day which I've only noticed recently is that you can become less reflective about the code because you don't get as much time where you're awake but not directly working with the code.

I frequently came up with possible ways to improve code bases on previous projects while playing around with something else or watching a presentation or similar.

I find that I play around with stuff outside the project less than I have previously partly because I've lost the 4 to 5 hour stretch that I used to have each evening.

On the positive side you get to know the people you're working with pretty well because you're with them for a lot more hours per day.

Not every project in the office has hours as stretched as mine but it certainly seems to be more common in India than elsewhere.
Distributed Agile: Bringing onshore people offshore
Date: 2010-12-20 08:58:35

For the last two weeks we've had a ThoughtWorks colleague from the onshore team working with us in Pune and it's been really cool having someone who has been working on 'the other side'.

In my time in India there seem to have been many more people going from offshore to onshore than the other way around but based on this experience I don't think that should necessarily be the case.

The typical argument in favour of someone from offshore going on site is that they're able to interact with the client and onshore people and pick up any required context which they'll then be able to share with their colleagues offshore.

The impact of those trips is perceived to be higher than what would be achieved by having someone do the reverse trip.

Having seen the interactions my US colleague was able to have with people has made me realise that perhaps that perception isn't as true as it seems.

A big part of the success of distributed projects seems to be about the ability for the two sides to communicate effectively and having someone who interacts daily with people that we only know by phone/email is very helpful.

My colleague was able to provide context about our client and what they're trying to do in a way that I don't think someone going onshore for a couple of weeks would be able to do.

Sometimes it's felt like we're just building something because we were told to do so and my colleague has been able to explain the underlying thinking and what we're trying to do with the system.

I think he's also found it a pretty useful experience in terms of learning about the strengths and weaknesses of the team and what the real pain points are.

Everyone offshore now knows one person onshore personally which should be useful for any future interactions.
Vim: Learnings so far
Date: 2010-12-27 19:15:51

I've been using Vim instead of http://www.jetbrains.com/ruby/index.html[RubyMine] for the last month or so and it's been interesting observing the way that I browse code as I add plugins to make my life easier.

== Between files

I generally don't know exactly where in the folder structure different files live since I'm used to being able to search by just the name i.e. RubyMine's Ctrl-N

http://yehudakatz.com/2010/07/29/everyone-who-tried-to-convince-me-to-use-vim-was-wrong/[Yahuda Katz wrote a blog post] earlier in the year where he listed some of the plugins he's been using - one of which is called https://wincent.com/products/command-t[Command-T] and allows exactly this functionality.

I also quite like the ability to quickly access files that I've recently opened i.e. files which are in the Vim buffer or RubyMine's Ctrl-E. The http://www.vim.org/scripts/script.php?script_id=1984[FuzzyFinder] plugin provides that functionality.

I've also tagged all my Ruby gems and the source code of the project using http://ctags.sourceforge.net/[Exuberant CTags] which then allows http://blog.bojica.com/2010/06/27/ctags-and-vim-for-ruby-on-rails-development[easy browsing to methods/classes].

== Inside files

I've noticed that the way I browse inside files has changed since I started using Vim.

I used to just scroll around files using the mouse but now I find myself moving around a file by line numbers instead.

A lot of the commands for file editing in Vim are based on moving/changing/deleting to a particular symbol so you become almost a human parser when reading a line of text.

I found/am finding the following quite useful for learning Vim shortcuts:

* http://www.viemu.com/vi-vim-cheat-sheet.gif[Vim cheat sheet]
* http://tnerual.eriogerg.free.fr/vimqrc.pdf[Vim quick reference card]
* http://jmcpherson.org/editing.html[Efficient Editing with Vim]

When coding in Java/C# I rely quite heavily on auto complete to tell me what methods I have available to me on a certain object.

Although I don't use it that frequently the http://www.vim.org/scripts/script.php?script_id=182[SuperTab] plugin works reasonably well when you do need help.

http://twitter.com/#!/just3ws[Mike] pointed out https://github.com/spicycode/Vimlander-2-The-Quickening[Vimlander-2-The-Quickening] which has some of the plugins I mentioned and several others ready to use.
India Cultural Differences: Hierarchy
Date: 2010-12-27 14:16:09

One of the more interesting differences between Indian culture and my own is that in India there appears to be more adherence to a hierarchy than I've experienced before.

ThoughtWorks tries to keep a reasonably flat hierarchy so I think the idea of hierarchy would be much more obvious if I was working at one of the big Indian services organisations.

Between peers conversations don't seem to play out any differently but someone in a position of authority is more likely to be able to get their opinion across and accepted with less resistance than they might experience without that authority.

On several occasions it's been only me and maybe a couple of others involved in discussions if someone in an authority position expresses an opinion assertively.

I asked several colleagues why this was and they pointed out that when they'd previously expressed an opinion in that type of situation it didn't have any impact so they'd stopped doing so.

I can't decide whether or not it really matters - the situations where authority has any influence are relatively infrequent - but it would be cool if all opinions were assessed just on merit.

Of course these are just my observations so it'd be interesting to hear others' experiences.
Why am I working in India?
Date: 2010-12-10 03:47:13

A few colleagues have asked me why I chose to work in India so I thought it would be interesting to explore what it is that appealed to me about working here.

I've come to the conclusion that there were 2 main drivers for me:

== The buzz of the ThoughtWorks office

I was in Bangalore in 2006 when I attended http://www.thoughtworks.com/thoughtworks-university[ThoughtWorks University] and one of the things that stood out for me was the atmosphere in the Diamond District office.

It was really buzzing with noise and I thought it would be really fun to have the chance to work in that type of environment.

I don't think Pune reaches the levels that I remember from Bangalore but it's still quite a fun and relaxed place to work.

I haven't noticed as much inter team communication in Pune as I did in Bangalore which is interesting and perhaps means we aren't getting the full benefit of having so many people in the same room.

My overall feeling is that the office here acts much more as a central point for people during the week and they'll spend much more time in it than I've seen in other countries.

The cool thing about that is that nearly every evening there's people to hang out and go to dinner with!

== Curiosity about offshore development

I've spent the past four years working predominantly in co-located teams and had always heard that it was much more difficult to work in a distributed team.

I have worked in one team which was distributed between Melbourne and Sydney but it's not quite the same as working in a team distributed in two countries with big time zone differences as well.

From hearing a couple of talks about distributed agile I was coming to the conclusion that big/complex projects would typically be off-shored since an offshore team could add people much more rapidly.

I haven't really noticed that my current project is any more complicated technically or domain wise than others that I've worked on but it certainly has significantly more people than anything else I've worked on before.

http://www.markhneedham.com/blog/2010/10/27/distributed-agile-communication/[As I've mentioned before], I do admire the patience of my colleagues in dealing with the slower feedback cycles/lack of face to face client communication which I've found very frustrating.