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.
So, given this class:
Why does the following unit test fail?
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".
Comments
return checked(_quantity += additionalQuantity);
So that runtime overflow checking is applied. You can also use /checked+ as a compiler switch instead of the statement or block.
_quantity += additionalQuantity;
return _quantity;
Just a wild guess. I didn't try running it.
C# projects have advanced build settings to check for arithmetic overflow/underflow. This is off by default so C# does not check for overflow and does not throw exceptions.
To pass the unit test without enabling overflow checks for the whole project and assuming only non-negative numbers are valid for the additionalQuantity field (yet another unit test) I would add the following guard clause:
if (_quantity > Int32.MaxValue - additionalQuantity) throw new OverflowException();
The default behavior is to round-up.
The simple of way of getting the exception to throw (and the test to pass) is to use the checked keyword so that the addition of the two integers is checked at runtime or you also set the /checked switch on the compiler to make sure that all integer arithmetic is overflow checked.