OdeToCode IC Logo

What's Wrong With This Code (#18)

Tuesday, October 9, 2007

Here is another golden oldie:

Numeric overflows are a type of software bug that occur when a calculation produces a result that doesn't fit in the intended storage location. One of the most famous cases of an overflow bug is the overflow bug that destroyed an Ariane 5 rocket in 1996*.

Fortunately, .NET has a dedicated exception to highlight overflow problems. Just run the following VB code and watch the OverflowException appear.

Dim i As Integer
i += Integer.MaxValue
i +=
Integer.MaxValue

So, given this class:

public class LineItem
{
    
private int _quantity;
    
public int Quantity
    {
        
get { return _quantity; }
    }

    
public int AddQuantity(int additionalQuantity)
    {
        
// some logic ...
        return _quantity += additionalQuantity;
    }

    
// other stuff...
}

Why does the following unit test fail?

[TestFixture]
public class LineItemTest
{
    [
Test]
    [
ExpectedException(typeof(OverflowException))]
    
public void TestForOverflow()
    {
        
LineItem lineItem = new LineItem();
        lineItem.AddQuantity(
Int32.MaxValue);
        lineItem.AddQuantity(
Int32.MaxValue);
    }
}

What options are available to fix the problem?

* The article Design By Contract: The Lessons Of Ariane says the real error was a "reuse specification error". Quote: "To attempt to reuse software without Eiffel-like assertions is to invite failures of potentially disastrous consequences".