1

I recently picked up Java and I was exploring the java.time package and noticed a, in my view, very nice interface where I could do ZonedDateTime.of(2015, 12, 1, …). Instead of the classical new ZonedDateTime(2015, 12, 1, …). I saw the same with a .from method to create the object from another object.

But just looking at the implementation without understanding why it's sometimes of and sometimes from I feel that I'm missing something. Especially since I'm now keen on using the same pattern for some of my own classes.

This being Java I'm assuming that there's an actual formal proper name for this, and not just something that the implementors of the java.time package made on their own. :)

gaqzi
  • 3,707
  • 3
  • 30
  • 30
  • 3
    [Static factory](http://stackoverflow.com/questions/929021/what-are-static-factory-methods-in-java). – Tunaki Mar 31 '16 at 14:44
  • 1
    [Item 1 in Effective Java 2nd Ed](http://www.informit.com/articles/article.aspx?p=1216151) is about static factories, and when to use them. Worth a read. – Andy Turner Mar 31 '16 at 14:50
  • Thanks, the links were super helpful! I'm a bit unsure how to close this question now though… – gaqzi Mar 31 '16 at 15:02
  • 2
    These are factory methods and the pattern is older than Java. Regarding the naming, usually `of(…)` is used to compose a value while `from(…)` will extract value(s) from a composed value, however, don’t think too much about it, there are plenty of other factory methods with different names. See for example [`Collections.singleton(…)`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#singleton-T-) – Holger Mar 31 '16 at 15:03
  • 2
    I don't think this is a duplicate. The other article talks about what a factory is, but doesn't address the naming conventions. – Brian Goetz Mar 31 '16 at 16:20
  • @Brian Goetz: can we expect some official words from the developer regarding naming conventions when we reopen the question? – Holger Apr 01 '16 at 10:38
  • @Holger We have some informal guidelines, which have been discussed on various OpenJDK lists, but no definitive rules. So "expecting" an "official" response is too strong, but "hope for useful/authoritative guidelines and advice" doesn't seem out of the question. – Brian Goetz Apr 01 '16 at 16:31
  • @Brian Goetz: the question is open now… – Holger Apr 01 '16 at 17:49

1 Answers1

2

The Java Tutorials has a chart explaining the various method prefixes employed in the api. See https://docs.oracle.com/javase/tutorial/datetime/overview/naming.html

Hank D
  • 6,271
  • 2
  • 26
  • 35