DEV Community

Sergiy Yevtushenko
Sergiy Yevtushenko

Posted on

Couple words about static factory methods naming.

There are few widely used approaches for naming of these types of methods, especially in general purpose classes.

  • getInstance() and alike
  • of()
  • with()

There are a lot of other variants, but they not so ubiquitous.

From my point of view these naming conventions looking so:

  • getInstance() is just plain ugly and verbose.

  • of()and with() are modern ones, widely used and for quite some time were my main approaches.

Recently I've hit one inconvenience with of()and with(): if I'm using them with static imports (for brevity) they loose clarity (hard to decide which of() or with() belongs to which class).

This is less an issue if there is only one such static import. But often I need in code several classes with such factory methods. In such case I can't do static import for both of them, so I ought to either use qualified name for all of them (and loose brevity) or use static import for one of them and qualified names for others (and loose clarity and brevity).

To resolve this issue I've decided to change approach and use lowercase name of class as a static factory method name. This enables me to use static imports for all such classes and preserve clarity and brevity:

   ...
   final var entries = map(1, "First", 2, "Second");
   ...
   final var topicList = list("One", "Two", "Three");
   ...
   final Promise<List<User>> friends = promise();
   ...
Enter fullscreen mode Exit fullscreen mode

All within the same file, clear and brief.

I'd like to know your opinion about this approach.

Latest comments (2)

Collapse
 
jacob87o2 profile image
Jacob B. • Edited

These "getInstance" and "with" methods you've mentioned are typically used differently.

For factory methods, I've seen many approaches, for example of, from, create. If the params can be used directly, I'd use of - Collection.of(users). If some conversion is needed, I'd use from - Money.from(someString) or Money.fromString(someString). If there is some complicated process and multiple params are involved, I'd use create - Player.create(stats, inventory, position, isFirstLogin).

Btw, I work mostly in other languages than Java but I think this approach is quite common across languages.

Collapse
 
siy profile image
Sergiy Yevtushenko

Thanks for your considerations. What you're describing has a lot of practical sense.