3.6. Making Error-Free Expressions
Problem
A complex expression in your code is returning incorrect results. For example, if you wanted to find the average area given to two circles, you might write the following expression:
double radius1 = 2; double radius2 = 4; double aveArea = .5 * Math.PI * Math.Pow(radius1, 2) + Math.PI * Math.Pow(radius2, 2);
However, the result is always incorrect.
Complex mathematical and Boolean equations in your code can easily become the source of bugs. You need to write bug-free equations, while at the same time making them easier to read.
Solution
The solution is quite simple: use parentheses to explicitly define the order of operations that will take place in your equation. If the expression is difficult to get right even when using parentheses, then it is probably too complex; consider breaking each subpart or the expression into separate methods for each part of the expression and then combine the methods to get the final result.
To fix the expression presented in the Problem section, rewrite it as follows:
double radius1 = 2; double radius2 = 4; double aveArea = .5 * (Math.PI * Math.Pow(radius1, 2) + Math.PI Math.Pow(radius2, 2));
Notice the addition of the parentheses; these parentheses cause the area of the two circles to be calculated and added together first. Then the total area is multiplied by .5. This is the behavior you are looking for. An additional benefit is that the expression can become easier to read as the parentheses provide clear distinction ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.