Search code examples
javajavabeans

Java beans and method realisation


There is a Java bean which has date setters/getters. The date is got from DB and set in the bean. When I get the date from the bean I need a particular presentation (yyyy-MM-dd instead of dd-MM-yyyy).

I want to simplify logic in the servlet and relevant classes by writing this part of code inside the bean's getter.
Is this an appropriate practice or not? Thank you in advance.


Solution

  • If you are 100% sure that you'll always need the date formatted that way, you can format it the way you want inside the bean mapping the database.

    However, you shouldn't.

    If you're looking for best practices, then you should keep in mind that reusable code should not depend on the implementation, and that a getter should do nothing more than retrieve the data. That's why I would suggest returning Date from the getter, and move the logic outside.

    Actually, if you don't want to rewrite code and you use always the same format, I would suggest a solution of this kind:

    YourMappingClass.java

    ...
    
    public Date getDate() {
      return this.date;
    }
    
    ...
    
    public String getFormattedDate() {
      Date dateToFormat = this.getDate();
      // format date here and return formatted date
    }
    
    ...
    

    This way you can preserve the getter's logic, and at the same time offer a reusable method inside the mapping bean to not repeat code outside of it.