Download presentation
Presentation is loading. Please wait.
Published byOlivia York Modified over 8 years ago
1
Refactoring Presentation Yash Pant
2
Overview 3 Refactoring Types: 1. Replace Error Code with Exception 2. Split Temporary Variable 3. Remove Middle Man
3
Replace Error Code with Exception Motivation: When code execution goes wrong, you have to handle errors. If you return an error code when something fails, the program will stop. Solution: Throw an exception instead of returning an error code, and let an exception handler manage the error. Benefit: Program execution won’t end if there’s an error, your handler can take care of whatever fails. You can eliminate conditional statements used to check for error conditions.
4
Replace Error Code with Exception - Example int authenticate(String credentials) { if (users.get(credentials) == null) return -1; else return 0; } Refactor to: void authenticate(String credentials) throws LoginException { if (users.get(credentials) == null) throw new LoginException(); }
5
Split Temporary Variable Motivation: Temporary variables can be reused many times to hold different values. If you use the same temp variable to hold values with different meanings, the code becomes hard to understand. Solution: Use a different variables for different values, so that each variable is responsible to hold just 1 value. Benefit: Code is more readable. Code is easier to change and maintain
6
Split Temporary Variable - Example double temp = revenue – costs; System.out.println(“Profit = ” + temp); temp = (costs / revenue) * 100; System.out.println(“Margin = ” + temp + “%”) Refactor to: double profit = revenue – costs; System.out.println(“Profit = ” + profit); double margin = (costs / revenue) * 100; System.out.println(“Margin = ” + margin + “%”)
7
Remove Middle Man Motivation: When your code becomes large, you can have too many classes that hand off tasks to one another. Solution: Delete the unnecessary methods and have them called directly instead of going through a chain of method calls Benefit: Code becomes easier to trace and debug Code is easier to maintain
8
Remove Middle Man - Example ShippingTracker Class Package getArrivalTime() Truck Refactor to: ShippingTracker Class Package getTruck() Truck getArrivalTime()
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.