javaconvenience-methods

Is there a better way to handle passing in multiple parameters to methods


I find myself doing the following a lot:

/**
 * Redirect to a MVC controller&action
 * @param controller
 * @param action
 */
public void redirect(String controller, String action) {
    redirect(controller, action, new HashMap<String, String>());
}
/**
 * Redirect to a MVC controller&action with extra URL parameters
 * @param controller
 * @param action
 * @param data
 */
public void redirect(String controller, String action, Map<String, String> data) {
    String urlParameters = "";
    for(String key : data.keySet()) {
        urlParameters += "&" + key + "=" + data.get(key);
    }
    m_binder.putLocal("RedirectParams", "IdcService=MVC_FRONTCONTROLLER&controller="+controller+"&action="+action + urlParameters);
}

To call the second method I actually need to create a hashmap to add data in it and I was wondering if there is a more convenient way of achieving this?

As you can see I need to know both the key and the value, so varargs wouldn't work (as far as I can see).

I'm open to all ideas, including using reflection.


Solution

  • I wrote this convenience method for build maps a while back. It takes varargs and makes a map out of them in pairs. For creating simple maps in test code, this is quite convenient. You need to make sure you get the numbers of parameters right but i like it because it makes the code volume smaller.

    @SuppressWarnings("unchecked")
    public static <K, V> Map<K, V> mapOf(K key, V value, Object... morePairs) {
        Map<K, V> map = new HashMap<K, V>();
        map.put(key, value);
        for (int i=0; i<morePairs.length; i+=2) {
            map.put((K)morePairs[i], (V)morePairs[i+1]);
        }
        return map;
    }
    

    Then you can create a map using:

    Map<String, String> map = mapOf("One", "1", "Two", "2");
    

    This is not everyone's cup of tea however (because of lack of type-safety) so you could change the implementation to take pairs:

    Map<String, String> map = mapOf(pair("One", "1"), pair("Two", "2"));
    

    Where you define pair as a static method that creates a simple object containing two values and then mapOf which converts those pairs into Entries in a Map.