Description
| publicintfunny(int a, int b) { int temp = a * b; if (temp > 100) { return temp * 0.95;
} else { return temp * 0.25; } } |
Consider the following code fragment.
Apply the following refactoring patterns to this code fragment:
- Inline Temp
- Extract Method Followed by Replace Temp with Query
- Discuss the two new code fragments, which refactoring pattern is more appropriate in thissituation? And why?
- Consider the following two code fragments.
| privateint currentBalance; intwithdrawFromBankAccount(int amountToBeWithdrawn) { if (amountToBeWithdrawn > currentBalance) return -1; else { currentBalance -= amountToBeWithdrawn; return 0;
} } |
| 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.
- Consider the following two code fragments (adapted from 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.
- Consider the following two code fragments.
| 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.



