How to I reduce the If condition in my Application | Core Java Training
20% Super Sale Discount Avail Now

Core Java Training Forum

How to I reduce the If condition in my Application

R
Rajeev Post on 22/11/2018

Hi,

I wanted to know a better way to code this scenario:

So in my application based on the request received,
If request.type ="Type 1"
set some parameters
load certain payload template
do certain operation
Similarly for Type 2 and Type 3

I was thinking of making Class for Type1, Type 2 and Type 3  and when I receive the request based on the type - load the class at runtime or use GEnerics. I am not sure how it can be done. Any guidance would be a great help

Y

Instructor

Yogesh Chawla Reply on 22/11/2018

Hi Rajeev,

You can create static or non static inner class for each and every request type and define specific functionality according to that very request type in that very inner class.

Static or Non static inner class can be decided based on the variables and methods involved whether they are going to be unique for each and every object or same for all objects. For this you need to check module 7 of our course. 

Generics are majorly used when same functionality is going to be implemented for different data types or different wrapper classes or different custom classes involved but in your case, i think functionality is going to be different for different request types so this can't be used.

R
Rajeev Reply on 22/11/2018

Hi Yogesh,

The functionality is more or less the same
but based on the type - the payload template, the end point and some other parameters are specific to that type.
I can do that using If condition i.e. If Requesttype = "Type1" then endpoint = "https://abc.com" and accounttemplate = type1Accounttemplate.flt and infotemplate = type1infortemplate etc
same for type2 and Type 3.
I am trying to eliminate the 'if' condition.
I was thinking thst I would create 3 Classes for each Type and have same name properties. So at runtime if I get Type1 then using reflection create an object of Type1 and in code I can get the properties( tmpalte, endpoint) related to Type 1. I am not sure how that can be achieved so wanted guidance.