简体   繁体   中英

What's the preferred Java convention for naming static constructor methods

What is the preferred convention for naming static constructor methods? For example, say I have an Error class, which has a single constructor which simply initialises the fields, and then some static constructor methods:

class Error {
    static Error xxxx(String msg) {
        return new Error(msg, -1);
    }

    static Error xxxx(String msg, int line) {
        return new Error(msg, line);
    }

    final String msg;
    final int line;

    private Error(String msg, int line) {
        this.msg = msg;
        this.line = line
    }
}

What should I name the xxxx methods. Possibilities include:

  1. valueOf - some Java classes follow this, eg Integer.valueOf , but is this only used for boxing primitives?
  2. of - more terse. Error.of(msg, i) seems readable.
  3. error - some pros and cons - see below.
  4. create - gives undue emphasis to the mechanism (create something) instead of the intent (give me a value). For instance, some implementations may cache and re-use values, meaning something isn't always actually created as such.
  5. createError - wordy, and same issue as create .

I tend to code in a functional style, and, possibly as a consequence, my preference was #3, partly because if I static import Error then I can call it simply as error(msg, i) , which seems readable and mimics actual constructor usage. However, it may cause confusion with local variables of the same name. For example error = error(msg, i); looks confusing.

I would be interested in seeing evidence or arguments in favour of a particular approach, rather than simple "I like xxx" answers.

If the recent JDK additions are a good indication, then you could look at java.time :

The API has a relatively large surface area in terms of number of methods. This is made manageable through the use of consistent method prefixes.

  • of - static factory method
  • parse - static factory method focussed on parsing
  • [...]

of looks like a reasonable candidate for your use case, but what probably matters more than the choice is consistency.

In "Effective Java", in addition to "valueOf" and "of" that you've already mentioned, Joshua Bloch proposes the following:

  1. getInstance

  2. newInstance

  3. get Type (ie getError)

  4. new Type (ie newError)

A good name for this is newError(...) . It suggest the class is also a factory for itself.

valueOf and of can be used when the factory method uses some kind of cache such that the method invocation doesn't necessary create new instance.

newClassName or createClassName is for general factory methods where it always tries to create an instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM