Functions with side effects are just rude!

February 25, 2009 by mrdavidlaing
Filed under: .NET, Agile, Code smells, TDD 

Today I fell into a trap when using a function that had a side effect – it unexpectedly changed an input parameter; causing a later statement to fail. Debugging took an age!

For example, consider the following function:

1
      string StringReplace(string haystack, string needle)

If this function is side-effect free, we can use it without fear like this:

1
2
3
4
5
6
        string menagerie = "cat,dog,bee,llama";
        string catFreeMenagerie = StringReplace(menagerie, "cat");
        string beeFreeMengerie = StringReplace(menagerie, "eric");
 
        Assert.AreEqual(",dog,fish,llama", catFreeMenagerie);
        Assert.AreEqual("cat,dog,,llama", beeFreeMengerie);

However, if StringReplace() had the side effect of also changing the passed in haystack, then the second Assert would fail, because the first StringReplace has the unexpected side effect of changing one of its arguments.

Evans in the DDD book has quite a bit to say about this; arguing that having side effect free functions goes a long way towards making a supple design

Side effect free functions also make testing & refactoring easier (less state to worry about etc)

Remember, function that changes parameters entrusted is rude, and should not be trusted!

PS: Eric the half a bee lyrics

Comments

Tell me what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

You must be logged in to post a comment.

  • Tags

  • Latest del.icio.us links