0

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?

  • 1
    Why aren't you just using the generic representations directly? What purpose is served by wrapping the generic representations in type-specific classes? Doesn't that defeat the whole purpose of using generics? – Robert Harvey Dec 14 '14 at 21:45
  • Do you mean the "number" and "name" fields should be stored as Integer and String respectively in the DataUnit class? Somehow I ended up with this (felt more natural because different fields may have different implementations of "parse()") but if you think that's better then I can still change it. I would still have to implement some kinds of custom parse methods for each field though. – Wiener Boat Dec 14 '14 at 21:54
  • Get rid of the ABC. Detect the type using if([data] instanceof [type]) in your parse method. Throw an exception in the else statement if the type doesn't support parsing. I could write a very nice solution in C# but Java doesn't include a typeof() method to use types as it's own type for comparison. – Evan Plaice Dec 15 '14 at 6:43
1

I designed and implemented a hierarchy like this many years ago (before generics) so here are some comments. They may help stop you from repeating my mistakes :)

The proliferation of methods like parseNumber(), parseName() suggests that the class hierarchy needs adjusment, yet your hierarchy looks well designed.

My approach would be a combination of techniques suggested by Robert Harvey and mdolanci.

  • Create an abstract class that has a parse(String data) throws ParseException method. Your AField class looks to do this now, although I would reconsider the class name (I suggest BaseField).
  • Create overloads for IntegerField() StringField() etc, with suitable parse logic for the type. Again this is exactly what you are doing.
  • Your DataUnit class looks to be a container for an arbitrary list of fields, but has a couple of dedicated fields (number and name) that I don't quite understand. If every DataUnit must have a number and name, then they are correct. But they won't be duplicated should you add more concrete AField types like PhoneNumberField or ZipCodeField. For instance calling asZipCode() on a list of fields is incorrect, as the list might contain multiple ZipCodeField instances. You can of course add a findFirstZipCodeField() method that iterates down the field list using instanceof to find the first field of that type.

I also suggest you move the actual validation out into static methods in a separate class focussed on string validation (as suggested by @mdolanci), preferably packaged in a separate validation library that knows nothing about fields. The day will come when you want to reuse this logic in a REST interface, Android app or something you have not thought of yet. Not making this separation was one of my biggest design mistakes, and has led to unnecessary code duplication in our applications.

0

Just create helper class with static helper methods.

Example:

public class DataHelper {

    public static String asString(final Object value) {
        return asString(value, null);
    }

    public static String asString(final Object value, final String defaultValue) {
        if (value instanceof String)
            return (String) value;
        return defaultValue;
    }

    public static Number asNumber(final Object value) {
        return asNumber(value, null);
    }

    public static Number asNumber(final Object value, final Number defaultValue) {
        if (value instanceof Number)
            return (Number) value;

        // If necessary you can parse string values
        if (value instanceof String && ((String) value).matches("^[0-9]\\.?[0-9]*$"))
            return Double.valueOf((String) value);

        return defaultValue;
    }

    public static Integer asInteger(final Object value) {
        return asInteger(value, null);
    }

    public static Integer asInteger(final Object value, final Integer defaultValue) {
        Number rv = asNumber(value);
        if (rv != null)
            return rv.intValue();
        return defaultValue;
    }

    public static Double asDouble(final Object value) {
        return asDouble(value, null);
    }

    public static Double asDouble(final Object value, final Double defaultValue) {
        Number rv = asNumber(value);
        if (rv != null)
            return rv.doubleValue();
        return defaultValue;
    }

    public static String asPhoneNumber(final Object value) {
        return asPhoneNumber(value, null);
    }

    // Here you could return custom object instead of string (if needed)
    public static String asPhoneNumber(final Object value, final String defaultValue) {
        String rv = asString(value);
        if (rv != null) {
            // Do your transformations
            // ...
            return rv;
        }
        return defaultValue;
    }

    public static Boolean asBoolean(final Object value) {
        return asBoolean(value, null);
    }

    public static Boolean asBoolean(final Object value, final Boolean defaultValue) {
        if (value instanceof Boolean)
            return (Boolean) value;

        if (value instanceof Number)
            return ((Number) value).intValue() > 0;

        if (value instanceof String && ((String) value).toLowerCase().matches("true|false|1|0|yes|no"))
            return ((String) value).toLowerCase().matches("true|1|yes");

        return defaultValue;
    }

    // ... etc.
}

Usage:

public class Usage {

    public static void main(String[] args) {

        final Map<String, Object> sampleData = ImmutableMap.of(
                "name", "Sample name",
                "active", "1",
                "age", 37,
                "weight", "75.7"
        );

        final String name = DataHelper.asString(sampleData.get("name"));
        final Boolean active = DataHelper.asBoolean(sampleData.get("active"), false);
        final Integer age = DataHelper.asInteger(sampleData.get("age"), 0);
        final Double weight = DataHelper.asDouble(sampleData.get("weight"));

        // ... etc.

    }

}
  • 2
    Welcome to Programmers. The site encourages answers that explain the why behind the how. Your answer would be much stronger if you explained how this approach addresses the OP's specific questions. – user53019 Jan 15 '15 at 1:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.