1. Consider the following two code fragments. Which fragment is more understandable? And why? (Hint: Think code smells) A. doublepotentialEnergy(double mass, double height) { return mass * height * 9.81; } B. static final double g = 9.81; doublepotentialEnergy(double mass, double height) { return mass * g * height;
} 2. Consider the following code fragment.
publicintfunny(int a, int b) { int temp = a * b; if (temp 100) { return temp * 0.95;
} else { return temp * 0.25;
}
} Apply the following refactoring patterns to this code fragment:
A. Inline Temp
B. Extract Method Followed by Replace Temp with Query
C. Discuss the two new code fragments, which refactoring pattern is more appropriate in thissituation? And why?
} privateint currentBalance; voidwithdrawFromBankAccount(int amountToBeWithdrawn) throws BalanceException { if (amountToBeWithdrawn currentBalance) throw new BalanceException();// You can assume that BalanceException is defined currentBalance -= amountToBeWithdrawn;
} public static Long valueOf(long l) { final int offset = 128; if (l = - 128 && l <= 127) {// will cache return LongCache.cache[(int) l + offset];
} return new Long(l);
} B.
Which refactoring pattern has been applied to the first fragment to transform it into the second code fragment? Explain why the second code fragment is superior to the first fragment.
4. Consider the following two code fragments (adapted from java.lang.Long ). A.
B.
public static Long valueOf(long l) { if (l = - 128 && l <= 127) {// will cache return LongCache.cache[(int) l + 128];
} return new Long(l);
} Fragment A is translated into Fragment B by applying the Inline Temp refactoring; and Fragment B is translated into Fragment A by applying the Introduce Explaining Variable refactoring. Provide possible situations (or contexts) where it would be advantageous to apply either refactoring to the appropriate code fragment.
5. Consider the following two code fragments.A.
public class A { public intk(long i) { return 10;
}
} public class B extends A { public intk(int i) { return 20;
} public static voidmain(String[] args) {
System.out.println(new A().k(2));
}
} B.
public class A { public intk(long i) { return 10;
} public intk(int i) { return 20;
}
} public class B extends A { public static voidmain(String[] args) {
System.out.println(new A().k(2));
}
} Which refactoring pattern has been applied to the first fragment to transform it into the second code fragment? Explain the impact (upon the results from function test) of the transformation.