Information Technology Reference
In-Depth Information
execution after catching an exception when the strong guarantee is fol-
lowed. Anytime you catch an exception, whatever operation was attempted
did not occur. It did not start, and it did not make some changes. The state
of the program is as though you did not start the action.
Many of the recommendations I made earlier will help ensure that you
meet the strong exception guarantee. Data elements that your program
uses should be stored in immutable value types (see Items 18 and 20). You
can also use the functional programming style, such as with LINQ queries.
That programming style automatically follows the strong exception
guarantee.
Sometimes, you can't use functional programming for styles. If you com-
bine those two items, any modification to program state can easily take
place after performing any operation that might throw an exception. The
general guideline is to perform any data modifications in the following
manner:
1. Make defensive copies of data that will be modified.
2. Perform any modifications to these defensive copies of the data. This
includes any operations that might throw an exception.
3. Swap the temporary copies back to the original. This operation can-
not throw an exception.
As an example, the following code updates an employee's title and pay
using defensive copy:
public void PhysicalMove( string title, decimal newPay)
{
// Payroll data is a struct:
// ctor will throw an exception if fields aren't valid.
PayrollData d = new PayrollData (title, newPay,
this .payrollData.DateOfHire);
// if d was constructed properly, swap:
this .payrollData = d;
}
Sometimes, the strong guarantee is just too inefficient to support, and
sometimes you cannot support the strong guarantee without introducing
subtle bugs. The first and simplest case is looping constructs. When the
code inside a loop modifies the state of the program and might throw an
 
Search WWH ::




Custom Search