Question

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?

-Ankit

Was it helpful?

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.

OTHER TIPS

There is no official standard, but this is my opinion,

valueOf or acquire implies that you will get any instance which holds the same information.

newInstance or create implies you will get a different instance every time.

get implies you will get an instance if it exist, or null if it does not.

In your case newInstance or create is appropriate.

c.f.

Integer.valueOf(1) == Integer.valueOf(1) // you get the same object
Integer.valueOf(-200) != Integer.valueOf(-200) // you get a different object.

In general, in java, String.valueOf() is called when a string representation of some other type of data is needed. In the case of primitive wrappers (Integer, Double), valueOf() takes a String ("12") and creates an instance of that wrapper.

In your case, you try to create a new object using a number of parameters. That is a factory method. It makes more sense to call it newInstance.

You answered your own question when you said And If I want to provide a static factory method to creating instances of this class new Instance makes sense in this context (even if both valueOf and new do the same). To me valueOf (as the name suggests )makes sense when you want to retrieve some meaningful state information from an existing object (not necessarily the entire object state) where as new is creating brand new instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top