Search code examples
javadesign-principles

How to use open closed principle for web page operations invocation in java?


I have a web page where users can fill in and submit forms:

 <form id=email...
 send email ....
 <input type="hidden"id="method" value="sendemail"...
 />
  .............

 <form id=writeindatabase
 some data
      ............
 <input type="hidden"id="method"  value="writeindatabase"...

On the server side:

if (method.compareTo("sendemail")==0) {
 doSendEmail(....
}
else if (method.compareTo("writeindatabase")==0) {
  doWriteInDatabase(....

 ..............................

I don't like this architecture because it violates the open close principle. Is it possible to refactor this to fix that? Thanks.


Solution

  • You can use reflection in a structured, secure manner, or, similarly the Command Pattern.

    • Reflection: make a Map<String, Method> that maps each acceptable method name to a Reflection Method object which you can invoke after looking it up.

    • Command Pattern: use a Map<String, Callable<?>> in a manner similar to above. Instantiate the Callables as anonymous inner classes that implement call by invoking the appropriate service method.