Search code examples
javadesign-patternsconcurrenthashmap

Why would a map helper extending hashmap be useful? Why not just use hashmap?


In a large java code base in my recent job, I see the below code:

public class MapHelper extends HashMap<String, Object>{

    private static final long serialVersionUID = 1L;

    public MapHelper() {
        super();
    }

    public MapHelper(MapHelper mh) {
        super(mh);
    }

    public MapHelper as_dict(String key) {
        return (MapHelper)this.get(key);
    }
}

I'm not sure how this would be useful. Are there examples you have that could shed light on the above MapHelper's usefulness?


Solution

  • The class does seem relatively frivolous the way it is now; however:

    1. It lets them refer to HashMap<String, Object> as MapHelper which is shorter and guarantees consistency. See also 'Is there a Java equivalent or methodology for the typedef keyword in C++?'.

    2. as_dict is a utility method that performs a cast. They appear to have foresight about what the Map contains. This is safer than doing the cast inline because the cast is defined in only one place. Less margin for error.

    3. It lets them add additional functionality later without having to update the entire code-base.

    4. Extending HashMap as a top-level class makes the generic type arguments reified, that is, they are available at runtime through reflection. See this blog post by Neal Gafter that explains this feature in more detail.

    So there are actually quite a few small but legitimate reasons to do this.

    There are some examples like this in the Java API such as: