Is there any convention for methods 'converting' an object into another? (toX, fromY)

62 views Asked by At

this is my first question on Stack Overflow; it is more of a curiosity that's interested me, because i've seen both being used.

I have a MapFile class and a Map class. MapFile objects can 'turned into' Map objects. Which one of these is the preferred way? Is there any?

in MapFile.java

public Map toMap(){
    Map map;
    // code to make a map
    return map;
}

OR

in Map.java

public static Map fromMapFile(MapFile f){
    Map map;
    //code to make a map
    return map;
}

Thanks.

1

There are 1 answers

0
Dmitry Gorkovets On BEST ANSWER

Preferred way is to create third utility class MapFileToMapAdapter and use it:

public class MapFileToMapAdapter {

    private MapFileToMapAdapter() {}

    public static Map toMap(MapFile mapFile) {
        Map map;
        // propagate map
        return map;
    }
}

In this case you will have loose coupling in your code: Map and MapFile will not know each other.