Re: Statements before super()
Tom Anderson wrote:
new SeparatedString("foo=bar", '=')
is equivalent to:
new StringPair("foo", "bar)
*/
class SeparatedString {
public SeparatedString(String str, char separator) {
// now what?
this(split(str, separator));
}
}
private String[] split(String str, char separator)
{
...
}
private SeparatedString(String[] strings)
{
super(strings[0], strings[1]);
}
I refuse to be concerned about the cost of the allocation of the String
array.
Propoal:
What would, I think, solve this kind of problem neatly would be to let a
constructor delegate object construction to a static factory method, hiding
the use of the factory from the caller. Something like (I don't like the
"return" syntax much either)
public SeparatedString(String str, char separator) {
return createSeparatedString(String str, char separator);
}
private static SeparatedString createSeparatedString(String str, char
separator) {
...
}
Of course, you'd want Java to guarantee that
1. the returned value isn't null (easy)
2. the returned value is newly created (very difficult, unless we insist
that
A. the factory method be in the same source file, and
B. the assignment "retval = new XXX();" be in the body of that
method)
Oh, and for inner classes, the enclosing value would need to be passed
explicitly to the factory. OK, ignore where I said "neatly".