Java —if-else removal & Functional Polymorphism
if-else & switch statements are integral part for most Java Programmers.
There might be scenarios we should assess to replace if else conditionals.
Will discuss some scenarios and how to refactor it
- Single If else
The above code does not cause any bad impact to code or its maintenance, we can leave as it is or we totally hate using if , Use ternary operator.
2. Multiple If else statements with Equal Condition and a static result
The above code does not cause any bad impact to code either.we can leave as it is or if we totally hate using if , Use a Map.
3. Multiple If else statements with multiple Conditions and a dynamic result
The above code has the potential to grow big. Looking at it we could sense there might be multiple rules will come to play and it might violate Open Closed Principle .
There has been multiple articles across web to replace if else , by creating too many classes. I myself hate it, we might need an abstract way to replace these conditionals across our application.
What i am going to provide you is a generic functional approach these kindda problems.
All the condition blocks within method has two things:
- A condition to evaluate, which should return Boolean
- Block to execute , returns a particular type (say a generic Type T)
We will create a single Class which has two parameters
condition:Supplier<Boolean> — which accepts a condition and returns boolean
process:Supplier<T>— which accepts a block of statements and returns type T
Create Representation for Every Condition with enum
In this case we have three conditions
- TEN_PERCENT_DISCOUNT
- FIVE_PERCENT_DISCOUNT
- ONE_PERCENT_DISCOUNT
Note: Order is important
Create method to generate Rule based on condition & process
The return type for every block is Double. So the return type would be Rule<Double>
Create Rules
Create rules for different representations
The first parameter is condition
The second parameter is reponse
Create a map of Representation & Rules
Now we have all the rules for every representation.
We will create a map of all representations along with the rule to simplify computation
Compute results
- Iterate through all representation enums
- Filter By : Get the condition & for the representation and check its validity in the map
- apply the process to get the result
We can refactor further the same code and apply default return as well.
The Rule<T> class can be applied to any condition replacement across the application.
The entire source code is available here
The code used in article is available as hands on workshop at youtube