Java —if-else removal & Functional Polymorphism

Muthukumaran Navaneethakrishnan
2 min readMay 27, 2020
Cleaning Code

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

  1. 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.

No great impact here

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.

Don’t make much difference though

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:

  1. A condition to evaluate, which should return Boolean
  2. 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

  1. TEN_PERCENT_DISCOUNT
  2. FIVE_PERCENT_DISCOUNT
  3. 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

  1. Iterate through all representation enums
  2. Filter By : Get the condition & for the representation and check its validity in the map
  3. 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

--

--

Muthukumaran Navaneethakrishnan

Programmer works with Java, Javascript ,Clojure, Rust, Golang & Python.