0

I have immutable class and 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 I want to add the new constructor with "char" parameter, something like this:

public Test(char s) { if(Character.isLetter(s)) { stringParameter = "firstReallyLong" + s + "DefaultString"; } else { stringParameter = "firstReallyLongDefaultString"; } } 

How can I do it without the code repetition of the long string? I would like to call "this()" constructor in else branch but it's not possible.

0

4 Answers 4

2
public Test(char s) { this(Character.isLetter(s) ? "firstReallyLong" + s + "DefaultString" : "firstReallyLongDefaultString"); } 
Sign up to request clarification or add additional context in comments.

3 Comments

this doesn't answer the question... the string firstReallyLongDefaultString still needs to be repeated in this constructor
@Heuster that can easily be moved to a static constant
That would answer the question (unless the original constructor cannot be altered)
1

You also could chain them more explicitly, removing some 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 to be done as a private constant to avoid repetition.

1 Comment

You mean this rather than super.
1

Like this:

public Test(char s) { super(); if(Character.isLetter(s)) { stringParameter = "firstReallyLong" + s + "DefaultString"; } } 

2 Comments

This doesn't seem to compile
The property is final, this will not compile.
0

A factory method gives you more flexibility:

public static Test create(char c) { final String parameter; if(Character.isLetter(s)) { parameter = "firstReallyLong" + s + "DefaultString"; } else { parameter = "firstReallyLongDefaultString"; } return new Test(parameter); } 

This can't be inherited in subclasses, however if you want your class to be strictly immutable it should be final.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.