I have a data structure with data units containing different types of data. I've wrapped the data in "Field" objects so that each field is able to independently parse user input in a desired way.
public abstract class<T> AField {
protected T value = null;
public T getValue() {
return this.value;
}
// This is the main reason I'm using a custom Field class
public abstract void parse(String data) throws ParseException;
}
public class IntegerField extends AField<Integer>{
public void parse(String data) {
super.value = data.trim();
}
}
public class StringField extends AField<String> {
...
}
// Note this has the same type as StringField but different parse implementation
public class PhoneNumberField extends AField<String> {
....
}
public class DataUnit {
private AField[] fields;
private IntegerField number = new IntegerField();
private StringField name = new StringField();
public DataUnit() {
this.fields = new Field {
this.number,
this.name
}
}
public void parseAll(String... data) throws ParseException {
for (int i = 0; i < this.fields.length; i++) {
fields[i].parse(data[i]);
}
}
// Now the troublesome methods
public Integer getNumber() {
return this.number.getValue(),
}
public void parseNumber(String data) throws ParseException {
this.number.parse(data);
}
public String getName() {
...
}
public void parseName(String data) throws ParseException {
...
}
}
You can see how the number of methods would quickly go up as I add more types of fields to the DataUnit class or more methods to the AField class. DataUnit has to pass all the methods of all the Field classes forward because I'd rather not expose the Field objects directly to other classes. What's the best way around this method mess? Are there better patterns to achieve this?