Java constructor chaining and avoid code repetition -
i have immutable class , want add new constructor without duplicating code in both constructors.
i have class:
public class test { private final string stringparameter; public test() { stringparameter = "firstreallylongdefaultstring"; } public test(string s) { stringparameter = s; } }
and want add new constructor "char" parameter, this:
public test(char s) { if(character.isletter(s)) { stringparameter = "firstreallylong" + s + "defaultstring"; } else { stringparameter = "firstreallylongdefaultstring"; } }
how can without code repetition of long string? call "this()" constructor in else branch it's not possible.
you chain them more explicitly, removing code repetition:
public class test { private static final string default_value = "firstreallylongdefaultstring"; private final string stringparameter; public test() { this(default_value); } public test(string s) { stringparameter = s; } public test(char c) { this(preparestring(c)); } private static string preparestring(char c) { if(character.isletter(s)) { return "firstreallylong" + s + "defaultstring"; } else { return default_value; } } }
the "firstreallylongdefaultstring"
better done private constant avoid repetition.
Comments
Post a Comment