COSC: 11.4 Methods: Common errors
Figure 11.4.1: Copy-paste common error. Pasted code not properly modified. Find error on (2)
(1) public static double cel2Fah(double celVal) { double convTmp = 0.0; double fahVal = 0.0; convTmp = (9.0 / 5.0) * celVal; fahVal = convTmp + 32; return fahVal; } (2) public static double fah2Cel(double fahVal) { double convTmp = 0.0; double celVal = 0.0; convTmp = fahVal - 32; celVal = convTmp * (5.0 / 9.0); return fahVal; } -forgot to change the return statement to return celVal rather than fahVal
11.4.1: Copy-pasted sum-of-squares code. Original parameters were num1, num2, num3. Original code was: int sum = 0; sum = (num1 * num1) + (num2 * num2) + (num3 * num3); return sum; New parameters are num1, num2, num3, num4. Find the error in the copy-pasted new code below. 1. 1 | int sum = 0; | | sum = | (num1 * num1) + (num2 * num2) + (num3 * num3) + | (num3 * num4) |; | return sum; |
Solutions: 1. (num3 * num4) The programmer copy-pasted the last term but only changed the second num3 to num4.
11.4.3: Common method errors. Forgetting to return a value from a method with a non-void return type is a common error. A missing return statement will result in a compilation error. 1. Forgetting to return a value from a method with a non-void return type is a common error. 2. Copying-and-pasting code can lead to common errors if all necessary changes are not made to the pasted code. 3. Returning the incorrect variable from a method is a common error. 4. Is this method correct for squaring an integer? public static int sqr(int a) { int t; t = a * a; } 5. Is this method correct for squaring an integer? public static int sqr(int a) { int t; t = a * a; return a; }
Solutions: 1. True A missing return statement will result in a compilation error. 2. True Being aware of this common error will help to ensure you vigilantly modify any pasted methods to implement the correct functionality. 3. True This type of error may be hard to find, as sometimes the returned value might be correct. 4. No The return statement is missing. 5. No The wrong value is returned
Copy and paste
a common error is to copy and paste code among methods but then not complete all the necessary modifications to the pasted code. - saves time, can reduce errors by starting with known-correct code
return wrong variable
such as typing return convTmp; instead of fahVal or celVal. -The method will work and sometimes even return the correct value.
failing to return a value for a method
the omission of a return statement for methods that should return non-void values results in a compilation error such as "missing return statement" - void return type: method automatically returns upon reach the end of the methods statements