Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw Exception then Call Constructor?

So I'm building a test library that I will mainly use for personal use however I have a question.

With Java, if you have 2 or more constructors in your class, if you wish to call one from another, it must be the first thing you do. This is problematic for me as I have the below setup.

public Constructor(TypeA a, TypeB b, TypeC c) {
    if (c.getData() == null) throw new IllegalArgumentException("");
    this(a, b, c.getOtherData());
}

public Constructor(TypeA a, TypeB b, TypeD d) {
    // stuff happens
}

How can I do this, avoiding the, "Constructor call must be the first statement in a constructor" error?

like image 867
Spedwards Avatar asked Jul 13 '15 13:07

Spedwards


3 Answers

You cannot do what you want with constructors. Instead use a static factory method like this:

public static TypeThing buildMyThing(TypeA a, TypeB b, TypeC c) {
    if (c.getData() == null) throw new IllegalArgumentException("");
    return new TypeThing(a, b, c.getOtherData());
}

public Constructor(TypeA a, TypeB b, TypeD d) {
    // stuff happens
}
like image 145
bhspencer Avatar answered Sep 19 '22 02:09

bhspencer


One option (probably bad): Check for getData == null and throw the exception as first thing inc.getOtherData()`. That would be the first method being executed.

Other Option: Have a method like,

helper() {
    if (getData() == null) throw new Exception();
    return getOtherData();
}

and from you constructor, call c.helper() instead of c.getOtherData()

like image 37
Codebender Avatar answered Sep 21 '22 02:09

Codebender


How about creating a static factory method?

public static Constructor newInstance(TypeA a, TypeB b, TypeC c) {
    if (c.getData() == null) throw new IllegalArgumentException("");
    return new Constructor(a, b, c);
}

private Constructor(TypeA a, TypeB b, TypeC c) {
    this(a, b, c.getOtherData());
}

private Constructor(TypeA a, TypeB b, TypeD d) {
    // stuff happens
}
like image 29
Joseph Roque Avatar answered Sep 22 '22 02:09

Joseph Roque