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.

Top comments (0)

Create an Account!

👀 Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.