Troubleshooting Tip #7 - Beware of side effects
You are very sure that you have written the program syntactically right, logically right, but the output doesn’t seem to be the one you are expecting. You think that the logic is correct and the input is correct but still you dont get the expected output. One of the possibility for the failure of your code could be a side effect of a certain statement. Maybe you are hearing this term for the first time, but I am sure after looking at the below example you would say “Oh is this called side effect?”
public void foo(int x, int y) {
if (x > 30 && (y=x*2) > 30) {
x = x + 10;
} else {
x = x + 5;
}
}
Assuming the above code is a java code, if I pass a value of 10 and 30 to x and y respectively what values of x and y do you expect once the if condition is executed? If your answer to this was 15 and 60 for x and y respectively then you are wrong. What happens here is a side effect. Remember the truth table of logical gates? Lets look at the truth table of AND gate.
| X | Y | Output |
| 0 | 0 | 0 |
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 1 | 1 |
What it signifies is that if both the inputs are true then the output of AND is true, but otherwise even if one of the input is false then the output is false. Now consider in a condition when the first expression evaluates to false. Since the result of the overall condition is going to false, there is no use in evaluating the second expression, hence the second expression is not evaluated at all. In software engineering terms this is called short circuiting. Side effects could come in different forms and short circuiting is one of them. Side effect depends on the programming language execution style as well. Be on the lookout for one when you write the code. Side effect could happen when you try to use short cuts and try to be more cryptic in your code. In the above example the expression y = x*2 should be taken out of the if condition for the expected result.
Deprecated: Function ereg_replace() is deprecated in /home/techmasa/public_html/wp-content/plugins/sociable/sociable.php on line 64
Permalink
Cosmos









