Łukasz Woźniczka
Łukasz Woźniczka

Reputation: 1695

EJB, JPA business method into entity

i have got uml diagram from projectant and into entity i have got method getTotalPrice()

So this is my class:

public class UOrder {

   @OneToMany
   private List<Product> products;

   ....
   public BigDecimal getTotalPrice(){
   BigDecimal b = new BigDecimal(0.0);
   for(Product p : products){
   b.add(p.getPrice());
   }
   return b;

 }

}

It is good idea to do it like that ? logical busines into entity ? I have got only function in uml diagram not field totalPrice or something like that so i figure out that it must be like that ...

Upvotes: 2

Views: 598

Answers (3)

ireddick
ireddick

Reputation: 8428

As an alternate point of view (an active record style data mapping object is just the persisted data in a handy form - a value object), here's what I think:

Given that you've said that the method is business logic, and given the well known domain that @Anton talks about - it's a bad idea. If you hadn't said it was business logic, I'd have questioned why you cared about that total in your application.

As an experiment, consider re-naming your mapped class UOrderData, treat it as a value object, and have a UOrder class that implements the business logic at application level.

Upvotes: 0

Anton Bessonov
Anton Bessonov

Reputation: 9813

I think isn't bad, but I preferrer like (pseudo code):

public class UOrder {
    ...
    public BigDecimal getTotalPrice() {
        return PriceUtil.getTotalPrice(products);
    }
}

public class PriceUtil {
    public static BigDecimal getTotalPrice(List<Product> products) {
        return sum-of-products;
    }
    ... other userful and fancy price functions ...
}

because you usually need:

  • to calcuate VAT or
  • price of other class as Product or
  • price in other class as UOrder
  • and so on.

Upvotes: 0

dcernahoschi
dcernahoschi

Reputation: 15250

It's more like a matter of taste. For example, if you like Domain Driven Design philosophy it's a really good idea as the total price belongs to the UOrder class.

Upvotes: 2

Related Questions