This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I would appreciate it if some one could suggest me what to use insted of if else loops in the programme. I just know that useing number of if-else loop in the method is not a good practise but. What to replace it with?
Here's a simple example. Below is a class that calculates a discount;
I've only put three if-elses in this class, but imagine there are 15 or 20. The code would look pretty ugly with that many.
Now suppose I create the following interface and implementations of the interface:
Now my SalesManager class looks like this:
Granted, the refactored version actually has more lines of code, but it's a more elegant solution. It's easier for someone to figure out what the calculation of customer type "B" is, for example. Again, it's a judgement call. If I really only had 3 if-elses then I might not go to the trouble of refactoring. But if I had 3 now, and knew it might expand to many more, I'd definitely choose the 2nd method.