Search code examples
javaspringpojo

How a when to solve string / date field data type convertion in pojo?


This question is about application design practice. I am thinking how to solve situation with pojo and fields that in application exist in more data types.

In my pojo there is one Date field. When creating this pojo by hand I set Date, when I parse from XML I have to deal with String representation and when make it persistent with JPA it should be Timestamp.

What is in general best practise in these situation? Should that pojo has this field in two data type representations (String and Date) or only in one general Date and while parsing from String convert it into Date from String?

Question #2: how to convert this date value from String to Date - as static method in pojo class? On place it into some external utility class.

Edit #1: I use Builder pattern for these pojo-s.


Solution

  • I like when my domain classes have rich representation of Date - DateTime (joda). Joda provides tons of methods that let you manipulate the date so this is in my opinion the best choice. When I have to write the date into xml or database I convert them.

    You're using a Builder pattern so you can provide multiple methods that set the date. For instance:

    private DateTime createdOn;
    ...
    public Builder createdOn(final DateTime createdOn) {
        this.createdOn = createdOn;
        return this;
    }
    
    public Builder createdOn(final String createdOn) {
        this.createdOn = DateTime.parse(createdOn, dateTimeFormatter);
        return this;
    }
    
    public Builder createdOn(final Date createdOn) {
        this.createdOn = new DateTime(createdOn);
        return this;
    }
    

    Conversion between String and Date is just a simple call so I don't think that it has to be separate utility class. The other thing is formatter. It has to know in which format the date has been written into String. You'd probably be using the same format in 95% of cases so I would extract the formatter.