Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a C# example of unintended consequences

I am putting together a presentation on the benefits of Unit Testing and I would like a simple example of unintended consequences: Changing code in one class that breaks functionality in another class.

Can someone suggest a simple, easy to explain an example of this?

My plan is to write unit tests around this functionality to demonstrate that we know we broke something by immediately running the test.

like image 209
dgiard Avatar asked Aug 12 '10 21:08

dgiard


2 Answers

A slightly simpler, and thus perhaps clearer, example is:

public string GetServerAddress()
{
    return "172.0.0.1";
}

public void DoSomethingWithServer()
{
    Console.WriteLine("Server address is: " +  GetServerAddress());
}

If GetServerAddress is changes to return an array:

public string[] GetServerAddress()
{
    return new string[] { "127.0.0.1", "localhost" };
}

The output from DoSomethingWithServer will be somewhat different, but it will all still compile, making for an even subtler bug.

The first (non-array) version will print Server address is: 127.0.0.1 and the second will print Server address is: System.String[], this is something I've also seen in production code. Needless to say it's no longer there!

like image 132
Rob Avatar answered Sep 23 '22 00:09

Rob


Here's an example:

class DataProvider {
    public static IEnumerable<Something> GetData() {
        return new Something[] { ... };
    }
}

class Consumer {
    void DoSomething() {
        Something[] data = (Something[])DataProvider.GetData();
    }
}

Change GetData() to return a List<Something>, and Consumer will break.

This might seen somewhat contrived, but I've seen similar problems in real code.

like image 42
SLaks Avatar answered Sep 24 '22 00:09

SLaks