Test Driven Development (TDD) – A practical example

Recently the development teams here have been improving their coding skills by taking on the challenge of Clean code, a practice by Robert C. Martin (Uncle Bob) who has a number of very informative clean code books and clean code videos practised by many developers and to improve the quality of their code, so they can code faster.

If you want to go fast. If you want to get done quickly. If you want your code to be easy to write, make it easy to read. The only way to go fast—is to keep the code clean.

― Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

Clean code is not the topic of this post though, I’ll leave that for another day. Today I’m going over the practice of TDD – Test Driven Development.

It has a number of advantages:

  • The biggest and most important is that it eliminates fear of change – refactor or modify at any time with no fear.
  • Reduce debugging time by between 50-90% – imagine a group of developers and pick one, any time, sometime in the last minute everything that person was working on worked and all its tests passed. It doesn’t matter who, it doesn’t matter when. Being good at the debugger is not a desirable skill, being good at the debugger, means you are experienced at interacting with bad code.
  • Reduce defects
  • Unit tests are the best low-level design document. If you want to do something, you can just copy the test that does it.
  • Writing tests first will mean that you write code that is testable, in other words, decoupled.
    This in turn Saves time, reduces estimates, which reduces costs
  • Avoid the grand cleanup – which inevitably fails due to lack of tests.
  • Increased confidence in the quality of the code – in the example app, if the tests pass they ship it. Your tests are like a parachute to prove your system works, imagine you are working on the code a life support system that you yourself might need to use at some point. Would you trust a system with its tests, would you jump out of an aircraft with a parachute that has holes in it?
  • Writing tests afterword is procedural, it is required of you for your job, but it feels like extra work for little gain. You already know your code works, because you have manually tested it, the danger then is that you take shortcuts with your parachute.

The 3 Rules of TDD

  • Write only enough test code to make it fail
  • Write enough code to make it pass
  • Refactor then repeat

The cycle is only 30 seconds to a few minutes long but it leads to code which you can have confidence in, code which you can entrust your life to.

Take the following example, I’ve taken the liberty to fill in the first few steps as comments so you can repeat the steps and then expand on them.

The Example

Below, you will see the typical High School computing problem of building a calculator, the requirements are simple to start with but slowly grow with complexity, but this can easily demonstrate TDD. See the jsFiddle site for the example.

Requirements

  1. it needs be able to sum multiple values
  2. it needs be able to able to subtract multiple values
  3. it needs to be able to multiply multiple values
  4. it needs to be able to divide one value from another
  5. it needs to be able to work with floating point numbers
  6. it needs to be able to calculate the value of an input number to the power of another number.
  7. it needs to be able to calculate the square root of a value
  8. it should have the ability to take a string of calculation values and compute the correct result.
  9. it should be able to handle multiple operators at the same time.
  10. it should output values to 5 decimal places
  11. it would be good if it could have a text field and button that when pressed would validate and calculate a user input calculation.
  12. it would be good if it could generate the calculations from calculator buttons

The application is written in Typescript and uses Jasmine as the testing framework. It starts with the simplist failing test, implement the calculator class, which can easily be made to pass by uncommenting parts of the code above.

To simulate the cycle, uncomment each test one at a time then uncomment the respective code to make it pass. Repeat this process until all the tests pass and the begin the 3rd acceptance criteria “needs to be able to multiply multiple values”.

Write the failing test and then implement it in the same fashion.

Dynamically Call A Method, Using a String with Method Name

I was trying to set up a dynamic setup of algorithms in server side code which return true if they succeed, but I wanted users to be able to choose from a database generated list as to which algorithm they wished to run, unfortunately I wanted to be able to update the list dynamically without having to rebuild all the code, only the algorithm static class that contains the algorithm and the database that contains the names of all the classes but not modify the presentation layer.

After having a quick look around I found this code on an old faithful website codeproject.com with the perfect article which contained a simple solution to my problem.

Dynamically Invoke A Method, Given Strings with Method Name and Class Name by Matt Perdeck.

The solution I had only required some minor modification to make it work for me,

and to call it

Ever noticed how certain CSS style colours sound like porn star names….

Was reading this tweet and I was amused enough to share it.

If you have ever been designing or coding html pages you will most likely have come across CSS and the color attribute. Now many of us will have been using the hex code for the value, feeling slightly dirty about using the named colour values, like black, red, and white. but now there is even more reason to feel dirty with names like these that sound like the sort of thing which would be associated with providers of specialist gentlemen’s literature.

Alice Blue
Rosy Brown
Burly Wood
Deep Pink
Golden Rod
Pale Golden Rod
Honey Dew
Hot Pink
Misty Rose
Peach Puff
Sandy Brown
Papaya Whip

What the hell?! The annoying dots that have appeared in Visual Studio

I know this will have happened to someone else before me, but when I code I don’t look at the keyboard, fairly standard. Yesterday however I went to hit [ctrl] + S and instead hit something else entirely, and this happened.

view spaces screenshot Following this, I now had dots everywhere, it didn’t take me very long to notice that they seemed to represent the spaces and tabs I had used to indent my code, but for the foggiest I did not know what I did to trigger it or how to fix it.

Enter trolling through the Visual studio toolbars before eventually coming across the setting and disabling it. Edit > Advanced >View White Space (ctrl E, S). Ahh that would explain it.

WordPress Stylesheets and scripts broken because WordPress adds https

Recently I noticed that if I viewed this site on a different machine There were no styles, and none of the scripts were being run until I logged in, at which point I added an exception for the ssl certificate for the site. This site like many others I would imagine is on shared hosting which means that my hosting provider setup the ssl certificate, which is very nice of them but does have the slight drawback that the certificate does not match my domain, which in nearly every browser will flag up an error message if you try to access it using https. For me this is not really a problem as I know why this happens and I am the only one really adding to this site so I can just ignore it.

However recently as I said above I noticed on machines that did not have an exception fort he ssl certificate, they could not see any of the lovely styling. This was because for some random reason WordPress was automatically adding https instead of http in front of all the stylesheets, and because there is an err with the ssl in this site due to the domains not matching, nobody who was not me could see this site. A problem, yes I think so.

Luckily for me I came across this wonderful website that had the solution to my problem, well at least steered me in the right direction.

The Solution was quite simple after a little exploring, just comment out the line which makes it https in /wp-includes/link-template.php

Building code to pass an arbitrary string containing the name of an object property and replacing it with the value of that property using RegEx, Reflection, and Linq

I recently wanted for the outputs of a search to be configurable easily by an admin by storing a specially crafted string which would use the object returned by the query and only display certain parameters, the key was that different people could see different things. The solution was a specially crafted string containing the entire formatting of the output with sections of interest marked out by brackets.

My first problem was getting the names of all the properties within the object, as I didn’t want to have to change my code if the object changed, or if I one day decided to change the name of one of the object’s properties. I did this after playing around within System.Reflection and after searching for a while I eventually stumbled upon an answer within StackOverflow by one of the users @mythz.

Then simply using a little System.Linq code to filter the responses and RegEx to get the sections to be replaced.

Bah Symbols, dealing with non-unicode symbols in HTML pages

I recently had an issue with a scientist posting an abstract which contained the alpha and beta characters, as well as a few others and I was facing the issue that they were not appearing in the browser. Initially I thought this was because the browser was not rendering Unicode as it’s output format, and I went through several iterations of changing headers and adding meta-tags to output as UTF-8, which I really should have been doing anyway.

This however did not solve my problem, the problem was that the characters I was trying to display were not Unicode, they were symbols with a Unicode identifier of U+F061 and U+F062. What I tried at first was to encode the HTML characters to their HTML unicode entity, using the code found in a CodeProject article.

This while making it more accessible to the browser, also did not solve the problem as despite them being valid elements, the browser did not understand them. I discovered in the end the problem was down to the font. The Symbol font to be exact. So with a little modification to the method to include the font-family style attribute.

References

Learning about GUID’s

I have a have been puzzling over a problem where I need to create one-time keys to access a system. My question is, is this secure to use a Globally unique identifier or GUID for this key. The consensus is generally yes.

While section 6 “Security Considerations” of the RFC 4122 standard states

Do not assume that UUIDs are hard to guess; they should not be used as security capabilities (identifiers whose mere possession grants access)

For the particular use case there appears to be a consensus in the community that this is “secure enough”, it is used every day whenever you get a link in an email to reset you password. They typically use a Guid to identify the request, and as the Guid becomes invalid once it has been used, even if someone did steal your id, it would only be good for one request assuming it has not timed out (many services have a timeout of 30 minutes for these Guids to be used) or already been used which would cause the authentication to fail.

Guids are also apparently guessable because they are designed for uniqueness (i.e. using the current date and MAC address of the machine as the seed) to produce a 128-bit integer, this makes the identifier predictable which could be a problem. A problem which is easily overcome by doing a simple trick used in cryptography, add a random salt, using a cryptographically strong randomization. A person could predict the Guid potentially, but more unlikely to predict the Guid and the random value. Then if you add in Transport level security of sending the information over SSL to prevent someone listening in (though if it is being sent it is being used so would be immediately invalid).

Sources

Removing empty entries from a string array

I recently answered this question on stack overflow: Find and remove items from array in c# which is in the format below.

In this case the items to be removed are whitespaces. So the simple solution would be to use Linq which can easily filter out entries where they are empty and return the filtered array.

Another possible solution is to skip the problem entirely. This would depend on how the array is filled in the first place, but if you were splitting a string which is how I would typically end up with this kind of array, you can do the below. This would mean that empty entries would never get into the array.