1

I'm reading the code base of a project, and here's some code I can't under stand:

protected BaseApiCommand(String apiName, ApiParams params, boolean isGetRequest) {
    this.apiName = apiName;
    this.apiParams = params;
    this.isGet = isGetRequest;
    if (apiParams == null) {
        apiParams = new ApiParams();
    }
}

public static BaseApiCommand createCommand(String apiName, boolean isGet, ApiParams params) {
    return new BaseApiCommand(apiName, params, isGet);
}

I know it's about publication, but I just can't understand why it's unsafe otherwise to expose the constructor directly. Can anyone explain it in detail ?

Marvin
  • 1,726
  • 1
  • 17
  • 25
  • 1
    I can't see anything this is todo with thread safety. This appears to be about using Factory methods instead of constructors directly. – Peter Lawrey Mar 06 '14 at 01:40
  • possible duplicate of [Java leaking this in constructor](http://stackoverflow.com/questions/9851813/java-leaking-this-in-constructor) – Gray Mar 06 '14 at 01:43

1 Answers1

0

In fact the static function is a static factory method to the class, as proposed by Joshua Bloch in Effective Java. This is a very common pattern in Java language and protects the constructor from the class consumers.