2

I am currently using a front controller pattern for my servlet and utilize a large if-else if structure in the doGet() and doPost() methods; however, my application is starting to add more and more functionality and as result the if-else blocks are getting out of control. I was wondering what are some popular strategies for handling this type of situation (while maintaining a front controller).

All I could think to do was maybe use a hashtable that maps paths (from the request url) to helper methods that determines the appropriate JSP (and sets attributes).

I liked the look of the Spring framework; however, I am currently not able to port to a framework, how does something like Spring avoid the problem I am facing?

2 Answers2

1

Independently of the framework or technology, I've faced several times your case and what I always do is to use a command pattern:

https://en.wikipedia.org/wiki/Command_pattern

and in the command handler I use a Factory pattern that instantiates the appropriate class to handle the request with the information of the command object.

With this architecture you are veeery flexible and it is quite easy to implement :)

Rafa
  • 2,328
  • 3
  • 27
  • 44
  • Going to do this for a school project.....thanks....teacher has us doing nested ifs and everything else....the final project he has given us freedom to do what we want..... – Grim Dec 06 '16 at 14:37
0

Use the Replace Conditional with Command Refactoring "pattern" described in Refactoring to Patterns.

Instead of

if(conditionA){
  //...
}else if(conditionB){
  //...
}
 ...

Do :

Handler handler = LookupHandlerBy(condition);
handler.execute();
dkatzel
  • 31,188
  • 3
  • 63
  • 67