In my class I have a condition statement which is very large
If (condtion1 ,condition 2,condtion4)
Set of statement
Else condtion 13
Set of statement
Condtion 5,condition 6,
Set of statement
Condtion 7 condtion 8 condtion 9
Set of statement
else condition 10 ,condition 11,condition 12
Set of statement
.
Since I every thing hard coded in If loop, I do not want to use it,
How I can replace the If loop with more generic stuff, which allow me to add more conditions and remove more conditions?
Gerardo Tasistro
Ranch Hand
Joined: Feb 08, 2005
Posts: 362
posted
0
A switch statement would be helpful first approach if your conditions are numeric.
Are your conditions something like variableX=1 (a number)?
Will you be operating on the same data on your statements? That is, you could put that in a method who's parameters would be the same even if what each method does is different?
As Gerardo said, the best answer for this may depend on the nature of the decisions you have to make.
Sometimes things like this can be encapsulated in a simple jump table (which in Java looks like a map of conditions => interface implementatons).
Hong Anderson
Ranch Hand
Joined: Jul 05, 2005
Posts: 1936
posted
0
You could use Factory and Command patterns.
Use Factory to create a command object and call command.execute().
SCJA 1.0, SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCJP 5.0, SCEA 5, SCBCD 5; OCUP - Fundamental, Intermediate and Advanced; IBM Certified Solution Designer - OOAD, vUML 2; SpringSource Certified Spring Professional
kitarp Prabhu
Greenhorn
Joined: Nov 12, 2008
Posts: 1
posted
0
implementing Factory (Abstract Factory - if needed depending on the complexity) with Command pattern is good solution.
Laurent Leonard
Ranch Hand
Joined: May 15, 2001
Posts: 35
posted
0
You could use the chain of responsability pattern (gof).
For each block in your if statement, you have a class that check if some conditions are validated, and if it's the case you can execute a statement.
Main -> Handler1 -> Handler2 -> Handler3 -> ... -> HandlerN
The advantages are
- different handlers could be triggered.
- Adding a new Handler is obvious.
- The condition are easier to read because no complex if statement.
- could be implemented in a way that if a statement is executed, the iteration on the chain is stopped
The disadvantage are
- be carefull of overlapping conditions (more than one statement is executed)
- testing could be difficult
Laurent LEONARD
Anand Kumar Singh
Greenhorn
Joined: Oct 18, 2007
Posts: 22
posted
0
Chain of Responsibility will be good for this scenario.