Here’s demo,
public class MyClass {
public MyClass(String str) {
if (null == str)
return;
mStr = processInput(str);
mMember1 = initMember1();
// ... some other initialization
}
Something like above, is it good or bad?
If it returned, we may get a constructed object without correct initialization.
It depends.
If your class can behave properly with a
nullbeing passed to the constructor and bypassing initialization, then it’s OK.If your class can’t, throw an exception, if not a checked exception then typically
IllegalArgumentException.It looks as though this constructor is a convenience constructor equivalent to:
If so, a better approach may be to use the fluent interface pattern, where methods return
this(where possible), so you can code:Here, the method
doSomethingWithString()instead of being declared asvoid, has a return type ofMyClassand the last line would bereturn this;. This pattern is handy for chaining up calls to methods, ieo.doX().setY(y).doZ();etc