views:

38

answers:

2

While developing my data model I didn't pay attention to the underlying database level. I encapsulated some logic in my domain classes' properties (example: method that counts order's profit). It all works well until I need to sort data. Sorting is a purely database feature (mainly because of performance i can't retrieve all rows from table and sort them on my domain level).
It turns out I have to repeat logic, previously encapsulated in my domain level in database level (not only repeat but translate it to database language).
It seems very bad thing and I don't want to do it.
Is there any way to bypass such problem?

Edit
example of what I'm trying to do:
my domain:

class Order {
  var lines;

  profit() {
    return lines.sum(line => line.sellPrice * line.quantity) - 
      lines.takeAllOutcomesAndSum(outcome => outcome.buyPrice * outcome.quantity)
  } 
}

class Line {
  var outcomes;
  var sellPrice
}

class Outcome {
  var buyPrice;
  var quantity;
}

the problem is when I want to sort orders by profit, it turns out to many joins and calculations in sql code (which repeat logic already written in Order.profit() method).
I've actually come to idea to store calculated values in the database instead of calculating them

A: 

Instead of this:

class Order {
  lines;

  profit() {
    return lines.sum(line => line.sellPrice * line.quantity) - 
      lines.takeAllOutcomesAndSum(outcome => outcome.buyPrice * outcome.quantity)
  } 
}

class Line { outcomes; sellPrice }    
class Outcome { buyPrice; quantity; }

Write this:

class Order {
  lines; profit;
  void Order(lines){
    profit = lines.sum(line => line.sellPrice * line.quantity) - 
      lines.takeAllOutcomesAndSum(outcome => outcome.buyPrice * outcome.quantity)
  }
}

class Line { outcomes; sellPrice; }    
class Outcome { buyPrice; quantity; }

Just make sure to keep it valid (update it every time order.lines changes) and it should be fine.

Arnis L.
that's exactly what I've already implemented. Writing queries now easy and straightforward. One little note: I've made such objects immutable to avoid possible data collisions
kilonet