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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With