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()
andwith()
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();
...
All within the same file, clear and brief.
I'd like to know your opinion about this approach.
Top comments (2)
These "getInstance" and "with" methods you've mentioned are typically used differently.
getInstance
is often used in singleton pattern, to get single instancewith
is used in fluent interface, to get object with something addedFor factory methods, I've seen many approaches, for example
of
,from
,create
. If the params can be used directly, I'd useof
-Collection.of(users)
. If some conversion is needed, I'd usefrom
-Money.from(someString)
orMoney.fromString(someString)
. If there is some complicated process and multiple params are involved, I'd usecreate
-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.
Thanks for your considerations. What you're describing has a lot of practical sense.