I'm sure this is really simple, but as I've just started coding Java, really, I can't figure out why this is happening. First, the code.
BusinessObject.java
PHP Code:
public abstract class BusinessObject {
public Vector validationMessage;
protected HashMap data = new HashMap();
public HashMap read () {
return data;
}
}
Person.java
PHP Code:
public abstract class Person extends BusinessObject {
public Person() {
}
public Person (String nameString) {
String newLast = "";
String newFirst = "";
if ( nameString.indexOf(",") != -1 ) {
newLast = nameString.substring( 0, nameString.indexOf(",") );
newFirst = nameString.substring( nameString.indexOf(",") + 1, nameString.length() );
} else if ( nameString.indexOf(" " ) != -1 ) {
newFirst = nameString.substring( 0, nameString.indexOf(" ") );
newLast = nameString.substring( nameString.indexOf(" ") + 1, nameString.length() );
}
Person(newLast, newFirst);
}
public Person (String newNameLast, String newNameFirst) {
data.put("nameLast", newNameLast);
data.put("nameFirst", newNameFirst);
}
}
When I try to compile Person.java, the compiler tells me that at the line Person(newLast, newFirst); inside the Person (String nameString) constructor, it 'cannot resolve symbol' on Person (java.lang.String, java.lang.String). I've moved the last Person constructor above the others, between the others, etc., but I know that shouldn't make a difference. I've tried casting newLast = (String) nameString.substring(... and THAT doesn't work.
I tried this(newLast, newFirst) before I posted, actually, and a different compiler error happens: "call to this must be first statement in constructor."
I've thought of replicating the actual data.put() calls into the Person(nameString) constructor, but at that point my understanding of the flexibility and convenience of overloaded methods breaks down sobbing and runs away into its stash of Xanax.
I don't like using the same ternary operation twice in the code. I don't like stretching argument definitions out like that. I don't like being so damned confusing that even clear indentation doesn't help the legibility.
Does that follow any recommended practices? It looks decent, but it seems to me that having a non-constructor method do the work of a constructor method would be frowned-upon. True, it works. True, I don't know a lot yet. True, I'm picking nits.
I don't know about any recommended practices, just going by common sense.
But I think that by making that method private you couldn't be violating too many recomendations. It's just a helper function that has some reusable code. There's no rule (or recommendation) against calling methods from the constuctor as far as I know. And since it's private it has no effect on the interfaces you expose, so it's effect on the architecture of the application is non-existant.
shmoove
Edit:
PS: If it helps you sleep better you can rename the method to something other than "construct". Call it "createData" or something. ;P