javafactory-methodcoding-style

What is the criteria to choose between valueOf() and newInstance()?


Suppose I have a class ObjectInfo which contains Object name & Object type as String.(I am just cooking up something for the sake of asking the question.)

class ObjectInfo {
    String objectName;
    
    String objectType;

    private ObjectInfo(String objectName, String objectType) {
          this.objectName = objectName;
          this.objectType = objectType;
    }
}

And If I want to provide a static factory method to creating instances of this class, which of the following two methods is better & why?

public static ObjectInfo newInstance(String objectName, String objectType) {
    return new ObjectInfo(objectName, objectType)    
}

public static ObjectInfo valueOf(String objectName, String objectType) {
    return new ObjectInfo(objectName, objectType)    
}

Basically, what I want to ask is when we should use valueOf() & when newInstance()? Is there any conventions among the programmer's community?


Solution

  •  public static ObjectInfo newObjectInfo(String objectName, String objectType)
    

    For a static factory method, I would use the above naming convention. This is useful if the method consumers want to use static imports:

    import static foo.ObjectInfo.newObjectInfo;
    //....
    ObjectInfo info = newObjectInfo(foo, bar);
    

    You can see this pattern in the Guava API.