Java – Wrapping a map with instance or static method

javaobject-oriented-designprogramming practices

I have a java.util.Map<String, Object> object which different types of values in it. I don't want to cast whereever I do a get operation over this. To do this, I created different classes wrapping this map and these classes provide different get methods which return values for different keys.

There are two options for this:

public class Wrapper1 {
    private final Map<String, Object> map;

    public Wrapper1(Map<String, Object> map) {
        this.map=map;
    }

    public MyObject getMyObject() {
        return (MyObject)this.map.get("someKey");
    }
}

public class Wrapper2 {
    private Wrapper2() {
    }

    public static MyObject getMyObject(Map<String, Object> map) {
        return (MyObject)map.get("someKey");
    }
}

As you see, in first one I'm creating an instance of Wrapper1 and access MyObject instance by instance method. In second, I give the map to a static method and access same MyObject instance.

Which one will you prefer more and why?
Also if this is a bad practice, please let me know.
Thank you.

Best Answer

This is still bad practice as you still do castings in there.

If you want to store different types in the map then the chance is high that all of these objects share a common behaviour. In this case all of these should implement the interface that defines this behaviour so that you can store them typesafe and without casting in the same map.

If they dont share the same behaviour then why store all in the same map? They will have different meanings and therefore should be saved in different maps or you create a class that has different maps of these types as members.

The last case is that you are given the array and you can't change the way the objects are saved. In this case I would actually prefer a combination of both your options. Put the static method into the class above. In this way you can commonly use the static function for getting your object without first creating an instance. If you know that you will need to call this method often, you can create an object passing the map and you will not have to always pass the map each time you want to get your object. This is related to using the fabric method pattern or currying / partial application used in functional programming (in which case the static method alone would be sufficient).

Note however that it would be good to somehow check if the object you get from your map satisfies your expectations (if possible) and otherwise throw an exception.