I have a codes table that stores name value pairs and a group name.
So for this example let me demonstrate with two rows, each row would represent one value in the same drop down.
Group Name = ‘Drop_Down_1’
Name = ‘Value 1’
Value = ‘This is my value’
Group Name = ‘Drop_Down_1’
Name = ‘Value 2’
Value = ‘This is my value 2’
This value would be apart of a drop down on a webpage. When selected and submitted the backend code would get the value ‘This is my value’, if that value in the drop down was selected. Now depending on the drop down selection I want to do something.
So now i need to compare the string in the request command to something.
What I do NOT want to do is something like this:
if(requestParam.equals('This is my value') {
do something
}
else if(requestParam.equals('This is my value 2') {
do something else
}
Now I can query the database and get the appropriate codes back and check against those for equality. But How would i know what action to perform?
1
Like MikeBabcock indicates, a variant of the Command Pattern is applicable here.
-
Create a structure that encapsulates the logic that you’ll want to execute:
public interface RequestHandler{ public void handleRequest(); } public class RequestHandlerImpl{ public void handleRequest(){ //do your thing } }
You’ll create implementations of
RequestHandlerImpl
to encapsulate the use-case specific business logic -
Hold instances of your handlers in a
Map
. Here,RequestParam
is a hypotheticalEnum
that corresponds to your dropdown menu’s items. I won’t recommend using the rawString
to handle thisMap<RequestParam,RequestHandler> handlers = new HashMap<RequestParam, RequestHandler>(); //this is going to hold your handlers
-
Using
RequestParam
(String arguments from your dropdown), you can pull the desired handler from the map, without anif
statement:public void execute(){ handlers.get(MY_VALUE_1).handleRequest(); }
I would only recommend this however, if you have more than 3 possible courses of action, based on your arguments. Any less than that, the above implementation might be overkill; a simple switch
statement on enums might be more effective and easier to read