2

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 ...

dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
Łukasz Woźniczka
  • 1,625
  • 3
  • 28
  • 51

3 Answers3

2

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.

dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
0

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.
Anton Bessonov
  • 9,208
  • 3
  • 35
  • 38
0

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.

ireddick
  • 8,008
  • 2
  • 23
  • 21