Archive

Archive for the ‘Test Driven Development’ Category

Creating Truth Tables. A Simple Truth Table for Programming Purposes

May 21, 2009 2 comments

David Cooksey Truth Tables

May 21st 2009 | David Cooksey

Truth tables are a handy method for quickly listing all the possible combinations for a set of inputs in logic.

Coincidentally, they are also very useful for doing the same thing in programming.

Let’s say you have a function that has 4 Boolean input parameters and you want to be sure it is mock tested with all the possible combinations. You could just eye-ball it, but chances are a combination or two have been forgotten. Enter truth tables!

As we have 4 variables with 2 values each, we know that we have 2^4 = 16 possible combinations. Create a table with 4 columns—one for each variable, and 16 rows—one for each combination. Then fill the table out as shown below. For verisimilitude we are using variable names that could have meaning in code.

US Citizen

Born In US

Gender

Born Before 1950

True

True

M

Yes

True

True

M

No

True

True

F

Yes

True

True

F

No

True

False

M

Yes

True

False

M

No

True

False

F

Yes

True

False

F

No

False

True

M

Yes

False

True

M

No

False

True

F

Yes

False

True

F

No

False

False

M

Yes

False

False

M

No

False

False

F

Yes

False

False

F

No

There is a simple pattern here, though it’s more apparent when using 1s and 0s or Ts and Fs instead of the more realistic data used here. The first variables column is half True and half False. The second is divided into quarters, alternating between True and False. The third column is divided into eighths, and the fourth is divided into sixteenths.

Let’s consider an example with 3 variables. The first variable is a Boolean; the second an enumeration consisting of three items; and the third a date. In this case the date has 4 ranges of data that change how it is treated in code, namely the four centuries between 1700 and 2000—18th, 19th, 20th, 21st.

2 * 3 * 4 = 24 combinations.

Boolean

Enumeration

Date (Century)

T

Item1

18

T

Item1

19

T

Item1

20

T

Item1

21

T

Item2

18

T

Item2

19

T

Item2

20

T

Item2

21

T

Item3

18

T

Item3

19

T

Item3

20

T

Item3

21

F

Item1

18

F

Item1

19

F

Item1

20

F

Item1

21

F

Item2

18

F

Item2

19

F

Item2

20

F

Item2

21

F

Item3

18

F

Item3

19

F

Item3

20

F

Item3

21

This pattern is marginally more complex. When filling out a truth table, start at the right side and rotate through the values going down. For all the columns following, rotate through the valid column values per the number of combinations in the preceding columns.

For example, let’s say you have the centuries laid out and you need to fill in the enumeration column. There are 4 valid values for the century column, so write down Item1 four times, then Item2 four times, etc., until the column is filled. For the Boolean column, there are 4 [century] * 3 [enumeration] = 12 valid combinations, so you write down T twelve times, then F twelve times.

The great thing about this method is that is simple and logical and can be used with any number of variables.

If you don’t use truth tables, how do you check that you have everything covered? Next time you’re programming a new algorithm, sketch out your truth table on paper, then use it to drive your unit tests and make sure you have everything covered.

David Cooksey is a Senior .NET developer at Thycotic Software Ltd, an agile software consulting and product development company based in Washington DC. Secret Server is our flagship enterprise password management product.

Who left the PartialMock out in the sun? It stinks!

Jimmy Bosse Partial Mocks

May 14th 2009 | Jimmy Bosse

Who left the PartialMock out in the sun? It stinks!

I recently paired with a developer to add functionality to an older piece of code. My pair typed in a line of code that almost gave me a heart attack:

ObjectUnderTest myObjectUnderTest =

mocks.PartialMock<ObjectUnderTest>(int someVariable);

I have an aversion to PartialMock like a vampire does to light. Its use is one of the putrid code smells I come across on a regular basis. But before I start a flame war let me preface my post by stating that there are many valid uses of PartialMock. It is very helpful when bringing a large legacy code base into a TDD environment, or when testing inherited objects. But most of the time, it’s more like a big block of gouda baking in a sunny kitchen window for a month or two.
Partial mocks are a sign that you might need to inject a dependency.

Imagine we are testing a Person class:

IPerson person = new Person();
Assert.AreEqual(true, person.IsAlive());

One of my qualifications for being alive is that my person must have a pulse, and luckily there is a HasPulse property on my person, so one might be inclined to:

Person person = mocks.PartialMock<Person>();
Expect.Call(person.HasPulse).Return(true);
mocks.ReplayAll();
bool isAlive = person.IsAlive();
mocks.VerifyAll();
Assert.AreEqual(true, isAlive);

Ugh.

Needing to fake out one part of my class to test another part is a sure sign that my class is doing too much. What my person needs is a heart. If I inject my person with a heart, my person can simply see if the heart is beating instead of asking itself if it has a pulse.

IHeart mockHeart = mocks.DynamicMock();
SetupResult.For(mockHeart.IsBeating).Return(true);
mocks.ReplayAll();
IPerson person = new Person(mockHeart);
bool isAlive = person.IsAlive();
mocks.VerifyAll();
Assert.AreEqual(true, isAlive);

Now when my test passes my person will be properly dependent on a heart. How the heart functions is separate from how my person relies on the heart.

public class Person : IPerson
{
    private readonly IHeart _heart;
    public Person(IHeart heart)
    {
        _heart = heart;
    }
    public bool IsAlive()
    {
        return _heart.IsBeating();
    }
}

Now imagine that my person needed more than a beating heart to survive, like lungs, liver, stomach, etc. If I had put all the code for each of these organs within my person, the class would get extremely complicated. Now I can make each organ function individually, and simply make my person dependent on his organs. So while it may seem like overkill now, with just a beating heart, by avoiding the partial mock in the beginning there is precedence for the next pair who works in this class to inject their organ when the client decides that the person needs a pancreas.

Refactoring Code: A Programmers Challenge Part 2

April 9, 2009 2 comments

Kevin Jones: Refactoring

April 9th 2009 | Kevin Jones

Refactoring Code: A Programmer’s Challenge

In a previous blog post– Refactoring Code: A Programmer’s Challenge Part 1—we went over refactoring basics, and took a not-so-easily-tested piece of code and made it easy to test.

Our final bit of code was this:

public class DisplayPanelDecider
{
    public bool ShouldDisplayPanelOnPage(string pageName)
    {
        string[] pagesToHideElement = new[]
        {
            "/index.aspx",
            "/sitemap.aspx",
            "/404.aspx",
            "/status.aspx",
            "/online_help.aspx",
        };
        return !Array.Exists(pagesToHideElement, s => s == pageName);
    }
}

The objective of the code is clear: “Given the name of a page, should I display a panel?”

Furthermore, the code is compact and does no more or less than it should – so we can test it easily.

Some of our tests would look like this:

[TestClass]
public class DisplayPanelDeciderTests
{
    [TestMethod]
    public void ShouldDisplayThePanelIfThePageIsNotInTheExclusionList()
    {
        DisplayPanelDecider decider = new DisplayPanelDecider();
        Assert.IsTrue(decider.ShouldDisplayPanelOnPage("/foobar.aspx"));
        Assert.IsTrue(decider.ShouldDisplayPanelOnPage("/main.aspx"));
        Assert.IsTrue(decider.ShouldDisplayPanelOnPage("/blog.aspx"));
    }

    [TestMethod]
    public void ShouldNotDisplayThePanelIfThePageIsInTheExclusionList()
    {
        DisplayPanelDecider decider = new DisplayPanelDecider();
        Assert.IsFalse(decider.ShouldDisplayPanelOnPage("/index.aspx"));
        Assert.IsFalse(decider.ShouldDisplayPanelOnPage("/map.aspx"));
        Assert.IsFalse(decider.ShouldDisplayPanelOnPage("/status.aspx"));
    }
}

An interesting side note: Did you notice that the names of our tests start with the word “should?” It’s such a simple thing, but the name of tests is important. One should be able to figure out the purpose of the test by reading its name. Using the prefix “should” forces you to think about the test name.

But as we know, software requirements grow and change. What’s happened to our software developer a few months down the line? (Put on your pretend cap!)

Well, at this point, his list of pages grown considerably. Rather than the handful we have in our code, we now need to hide the panel for many pages. As an additional requirement, it now needs be configurable too, so compiled code is not the best solution.

A natural place to put configuration for now is in the appSettings section of the web.config file, and for simplicity sake, we’ll separate our pages with a semicolon, so they’ll look like this:

<configuration>
    <appSettings>
        <add
key="PagesToHidePanel"
value="/index.aspx;/map.aspx;/404.aspx;/status.aspx;/online_help.aspx"/>
    </appSettings>
</configuration>

Now, we need a class that is responsible for retrieving these page names and parsing them. Rather than throw that code in our existing class, introduce a new dependency.

The implementation I came up with looks like this:

public interface IDisplayPanelExclusionProvider
{
    string[] GetPageNames();
}

public class DisplayPanelExclusionProvider : IDisplayPanelExclusionProvider
{
    public string[] GetPageNames()
    {
        string unparsedContent =
            ConfigurationManager.AppSettings["PagesToHidePanel"];
        string[] pageNames = unparsedContent.Split(';');
        return pageNames;
    }
}

Notice I created an interface. This will have a key role later on. The next step is getting our two classes, DisplayPanelExclusionProvider and DisplayPanelDecider talking to each other.

The constructor is a simple and useful approach to dependency injection. Our goal here is to get the DisplayPanelDecider to ask the DisplayPanelExclusionProvider, “On which pages should I not display this panel?”

We’ll modify the DisplayPanelDecider to take in a IDisplayPanelExclusionProvider. Again, notice I used the interface in this example. So our class now looks like this:

public class DisplayPanelDecider
{
    private readonly IDisplayPanelExclusionProvider _displayPanelExclusionProvider;

    public DisplayPanelDecider(IDisplayPanelExclusionProvider displayPanelExclusionProvider)
    {
        _displayPanelExclusionProvider = displayPanelExclusionProvider;
    }

    public bool ShouldDisplayPanelOnPage(string pageName)
    {
        string[] pagesToHideElement = _displayPanelExclusionProvider.GetPageNames();
        return !Array.Exists(pagesToHideElement, s => s == pageName);
    }
}

Our DisplayPanelDecider now asks the IDisplayPanelExclusionProvider for a list of pages. However, by introducing our constructor, we broke our tests! The next step is to start getting our tests working again.

Important note: even though our class examples seem contrived, we are keeping decision-making logic separate. This is important from the testability aspect as well as for future maintenance. The key part here is single dependency, and that applies for our tests as well. We don’t want our tests testing multiple classes at once: keep them separate.

This is where the interface saves us: we can inject our own classes for the purpose of testing.

[TestClass]
public class DisplayPanelDeciderTests
{
    private class MockDisplayPanelExlusionProvider : IDisplayPanelExclusionProvider
    {
        public string[] GetPageNames()
        {
            return new[]
                   {
                       "/index.aspx",
                    "/map.aspx",
                    "/404.aspx",
                    "/status.aspx",
                       "/online_help.aspx"
                   };
        }
    }

    [TestMethod]
    public void ShouldDisplayThePanelIfThePageIsNotInTheExclusionList()
    {
        DisplayPanelDecider decider = new DisplayPanelDecider(new MockDisplayPanelExlusionProvider());
        Assert.IsTrue(decider.ShouldDisplayPanelOnPage("/foobar.aspx"));
        Assert.IsTrue(decider.ShouldDisplayPanelOnPage("/main.aspx"));
        Assert.IsTrue(decider.ShouldDisplayPanelOnPage("/blog.aspx"));
    }

    [TestMethod]
    public void ShouldNotDisplayThePanelIfThePageIsInTheExclusionList()
    {
        DisplayPanelDecider decider = new DisplayPanelDecider(new MockDisplayPanelExlusionProvider());
        Assert.IsFalse(decider.ShouldDisplayPanelOnPage("/index.aspx"));
        Assert.IsFalse(decider.ShouldDisplayPanelOnPage("/map.aspx"));
        Assert.IsFalse(decider.ShouldDisplayPanelOnPage("/status.aspx"));
    }
}

Note that we are injecting a fake class that allows us to implement a hand rolled mock. The single purpose of this test class is to ensure that the DisplayPanelDecider decision logic works. It isn’t the DisplayPanelDecider’s responsibility to know the real list of pages from our configuration. That should be tested somewhere else. In effect, we are testing against dummy data. When we want our class to use the real provider, we just create an instance of that and hand it in. In fact, with constructor chaining we can implement a default constructor that uses the real provider:

public DisplayPanelDecider() : this(new DisplayPanelExclusionProvider())
{
}

We have the option of using the DisplayPanelDecider with the real provider, or handing in our own – which we do for testing.

Now the thought on most people’s mind at this point is most likely “This seems like overkill.” If you stand back and look at it for all it is now, I might agree. However, maybe the programmer we’re helping finds himself with more challenging requirements. The other part is the hand rolled mock.

Rewinding a bit, in our new tests we saw a dummy class that provided fake data for the sake of testing. There are mock frameworks that remove the need for these dummy classes, but we’ll examine that in a future blog post. If you’re up for some homework, check out Rhino Mocks.

I pose this question to you: What advantages and disadvantages do you see with our approach? Is it worth the effort? I’d love to know what you think.

Kevin Jones is a Senior .NET developer and Product Team Leader at Thycotic Software Ltd. Thycotic is recognized for providing Agile TDD Training and Agile .NET Consulting Services, and its flagship password management software Secret Server. On Twitter? — > Follow Kevin

Refactoring Code: A Programmers Challenge

April 2, 2009 4 comments

Kevin Jones: Refactoring

April 2nd 2009 | Kevin Jones

Refactoring Code: A Programmer’s Challenge

Today I encountered a question on the ASP.NET Forum that I got quite excited about, “How do I refactor this?” Refactoring is a big part of our daily coding practices and I was curious as to what other programmers would come up with. Here is the basic question re-worded a little bit for brevity:
I have a master page with a control on it. However, on certain pages I don’t want a control to be shown. At first it was just one or two pages, and my approach worked just fine. However, the number of pages I need to hide this control on has grown. Can anyone offer some advice on how to refactor this code?
This was his code:
string pagename = Request.ServerVariables[“PATH_INFO”].ToString().Trim().ToLower();
if (
pagename == “/index.aspx” ||
pagename == “/sitemap.aspx” ||
pagename == “/404.aspx” ||
pagename == “/status.aspx” ||
pagename == “/online_help.aspx”
)
{
SomePanel.Visible = false;
}

The original poster realized that his code wasn’t maintainable-a classic reason to refactor: Keep your code clean, readable, and maintainable.

The interesting thing about refactoring is that there is no de-facto way to improve this code-or any refactoring for that matter. Refactoring has a lot of patterns that have been used over the years, but how that pattern is implemented, and evolves, is a discussion that could go on forever. The key is: keep the code simple and keep the changes small. If we really wanted to, we could write over-the-top code; put these pages in a database table; and cache the table for performance. But if you refactor often enough the changes should always be incremental.

Here’s something else to consider: the ‘if’ statement will keep getting larger and larger every time a page is added. If I was implementing this I might have started in the same place. I wouldn’t have needed this control visible for this page, but then I might not have needed it for the next one either, or the next one. The original code is not bad-it just doesn’t meet the new criteria.
My suggestion is to remove the OR chain and store the page names in a local so one can just keep adding to a string array, and then check if it exists in the string array. This simple refactoring adds a little clarity to the code, but it’s not exactly a work of art:
string[] pagesToHideElement = new[]
{
“/index.aspx”,
“/sitemap.aspx”,
“/404.aspx”,
“/status.aspx”,
“/online_help.aspx”,
};
string pagename = Request.ServerVariables[“PATH_INFO”].ToString().Trim().ToLower();
if (Array.Exists(pagesToHideElement, s => s == pagename))
{
SomePanel.Visible = false;
}
We have isolated one of our problems: the growing list of pages we want to exclude. The developer can then keep adding to the array. This also provides flexibility we didn’t have before. We can now move our page list anywhere we like, like a new class and method. This is a very simple refactoring, but what else can we do? While the original person didn’t think of this, this code isn’t easy to test without a full-blown integration test.
Not to derail our refactoring discussion, but let’s talk briefly about testing and how it applies to refactoring. They go hand-in-hand, especially to an Agile developer. Refactoring is a necessary part of improving code, but how do you know that everything will still work? Many who oppose refactoring don’t write tests simply because they have no proof that a refactoring didn’t break the code. And refactoring isn’t always easy, especially when dealing with legacy code. Most Agile developers are familiar with the “Red-Green-Refactor” motto:

Refactoring Code

The diagram varies, but nevertheless it always says the same thing
1. Write a failing test first (That’s a core Test Driven Development value)
2. Make the test pass by implementing the required code
3. See the test pass
4. Refactor
5. Make sure you are still green
6. Improve test so that it is red again
It’s the fifth component that makes testing and refactoring go together well. Peace of mind comes with knowing that you didn’t break anything, assuming you have good testing practices-but of course you do!

Back to refactoring. How is this code refactoring tested without actually seeing if it shows the correct content or not? MVP or the MVC pattern are a good idea, but let’s start small. A pattern that I am fond of for these simple things is a decider class. The benefits of this pattern will become clear shortly.
This sort of decision-making logic doesn’t really belong in the presentation layer (UI layer). It can be deferred to a decider. The decider is exactly what it sounds like-a class that decides if the panel should be visible or not. So our decider can have a method on it that takes a page name, and return a Boolean value if the panel should be displayed. Simple enough, right? At this point we are extracting our logic out of the page and into a new class.
public class DisplayPanelDecider
{
public bool ShouldDisplayPanelOnPage(string pageName)
{
string[] pagesToHideElement = new[]
{
“/index.aspx”,
“/sitemap.aspx”,
“/404.aspx”,
“/status.aspx”,
“/online_help.aspx”,
};
return !Array.Exists(pagesToHideElement, s => s == pageName);
}
}
So now we have a piece of logic that we can test very easily. All that the ASPX page would have to do is create an instance and hand in the page name, but the core decision logic can be tested without any need for a browser.
This gives us a new power through. Now that we have this decision making logic in its own method, we can make our method do whatever we like. If, in a year’s time, this no longer feasible, we can alter our method to pull the page names from an XML file or a database. We’ll look at that later.


A quick recap of what we did:

  • We changed the functionality to give us a bit more functionality and moved from a large OR operation to a more dynamic approach.
  • We extracted our logic out to a new class.
  • Two simple changes…and the benefits are huge!
  • We can now test this logic very easily through our favorite testing framework. XUnit MSTest, etc. (I refer to XUnit as “Any of the testing frameworks, like NUnit, MbUnit, etc. Not the actual framework called “xUnit”).
  • Our logic extraction keeps the decision making out of the ASPX code behind. This keeps our ASPX code behind focused on the page, not buried in a code behind.
  • We have the freedom to change what this method does without affecting the page. In the future, we can make “ShouldDisplayPanelOnPage” do whatever we like.
  • Further changes to this class can be tested TDD style so we can feel confident that future refactorings won’t break functionality.

What would you have done to improve the code? Got a better idea or suggestions?
Next we’ll look at dependency injection and what happens when this decision making logic gets complex.


Kevin Jones is a Senior .NET developer and Product Team Leader at Thycotic Software Ltd. Thycotic is recognized for providing Agile TDD Training and Agile .NET Consulting Services, and its flagship password management software Secret Server.

Speaking on Refactoring at RockNUG in March

January 25, 2008 Leave a comment

I will be presenting on Refactoring in C# at the Rockville .NET User Group (RockNUG) on March 12th 2008 at 6:30pm.

Refactoring in C# – Bad code to better code
What could be more fun on a Wednesday evening than critiquing some bad code and making it better? 🙂 Come along to learn how to clean code like the Thycotic team. What do we look for? How do we take small steps to keep it working? What tips and tricks make it easier? This session will be code, code and more code (and a few unit tests of course!).

I always like Refactoring sessions because they give great opportunities for discussion about coding practices and also get lots of different opinions on how to improve the code.  I will be using Visual Studio 2005 and Resharper 3.0.

 

Jonathan Cogley is the CEO and founder of Thycotic Software, a .NET consulting company and ISV in Washington DC.  Our product, Secret Server is a enterprise password manager system for teams to secure their passwords.  Is your team still storing passwords in Excel?

Secret Server 4.0 has shipped!

December 22, 2007 Leave a comment

theming

We were hoping to ship one day early but a few delays in getting some updated artwork and some of the upgrade documentation caused us to ship yesterday on the scheduled day.  Secret Server has never missed a launch date since first being released in November 2005 – this is something we attribute to Test Driven Development, Pair Programming and an agile planning schedule.  Usually this means reducing scope slightly as the launch date approaches – this time we had to drop a fix for supporting backup when SQL Server is not on the IIS box but it will come in an update in early January.

So what is new in 4.0?

Theming

Theming allows you to create your own company theme for Secret Server – this was a popular request with customers. 

We also shipped two new themes with 4.0 – Blue Chrome and Corporate.

Inherited Permissions on Folders

Managing permissions on secrets and folders is tedious.  4.0 brings permission inheritance across secrets,sub-folders and folders.  This makes it possible to specify who has access at a high level and allow those rights to cascade through the hierarchy.

Additional Highlights

  • Optional, customizable Login Policy Statement for corporate environments
  • Migration from the Microsoft .NET Framework 1.1 to 2.0
  • Ability to search by sub-folder
  • More…

 

Jonathan Cogley is the CEO and founder of Thycotic Software, a .NET consulting company and ISV in Washington DC.  Our product, Secret Server is a enterprise password manager system for teams to secure their passwords.  Is your team still storing passwords in Excel?

Do you have what it takes to be a Thycotic TDD Developer?

October 11, 2007 5 comments

thycotic Thycotic is gearing up for a new product development cycle and we are looking to grow our team of passionate test-first developers. Our team is one of the best places to learn and improve your agile development skills.

Can you solve the problem below?
http://www.thycotic.com/codetest.txt

Please submit your solution with your resume to tddjobs@thycotic.com

You willbe joining a highly capable team of .NET developers who work on consulting projects for clients and interesting products such as Secret Server.

Requirements:

  • You want to develop using Test Driven Development (that is *ALL* we do!)
  • You live, breathe, sleep, eat and drink code of the C# or VB.NET flavor
  • You enjoy or are excited about Pair Programming
  • You have a strong understanding of Object Oriented principles, the .NET Framework, ASP.NET, relational databases and web application development
  • You have the permanent legal right to work in the United States
  • You have excellent written and spoken English
  • You are able to communicate effectively with co-workers and clients/customers
  • You are willing to work in the Washington DC Metro Area

Why come to Thycotic?

  • We always practice TDD and Pair Programming
  • We are a Microsoft Gold Certified Partner
  • Your ideas and opinions will be valued
  • You will be working in the heart of Washington, DC
  • You will continually learn about new development techniques and technologies

PLEASE NO RECRUITERS, THIRD PARTIES, INDEPENDENTS OR OFFSHORE COMPANIES.