views:

16

answers:

1

I have a persistence related java-ee code which I need to rewrite to make the app work on the Google App Engine and its data storage. When I use java-ee persistence providers, I generate persistence entities with my IDE and I keep them the way they are in case I need to regenerate them. However autogenerating entity classes for app-engine storage is not possible and I would like to know if there are any good reasons why I should keep the entity classes clean and not use fields and methods not directly related to persistence. I use objectify as persistence provider if it matters.

Here's an example:

public class Dog {
  @Id Long id;
  @Transient Integer barkCount;

  public String bark() {
    barkCount++;
    return "woof-woof";
  }

  public String getAgeEstimation() {
    switch(barkCount) {
      case 0:     return "unborn (or very lazy)";
      case 10000: return "this is very old dawg";
      default:    return "you get the idea :)";
    }
  } 
}
+1  A: 

I would like to know if there are any good reasons why I should keep the entity classes clean and not use fields and methods not directly related to persistence.

There is nothing wrong with adding methods not directly persistence related but doing business things with data retrieved from the datastore - and actually implementing a Rich Domain Model (vs an Anemic Domain Model).

So, instead of having procedural style services, move the business logic inside a rich domain object. For example (taken from Domain-driven design with Java EE 6):

@Entity
public class Load {

    @OneToMany(cascade = CascadeType.ALL)
    private List<OrderItem> orderItems;
    @Id
    private Long id;

    protected Load() {
        this.orderItems = new ArrayList<OrderItem>();
    }

    public int getShippingCosts() {
        int shippingCosts = 0;
        for (OrderItem orderItem : orderItems) {
            shippingCosts += orderItem.getShippingCost();
        }
        return shippingCosts;
    }
//...
}
Pascal Thivent