Skip to content
Advertisement

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.)

JavaScript

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?

JavaScript

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

Advertisement

Answer

JavaScript

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

JavaScript

You can see this pattern in the Guava API.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement