The example below is totally artificial and its only purpose is to get my point across.Suppose I have an SQL table:CREATE TABLE rectangles (  width int,  height int );Domain class:public class Rectangle {  private int width;  private int height;  /* My business logic */  public int area() {    return width * height;  }}Now suppose that I have a requirement to show to the user the total area of all rectangles in the database.I can do that by fetching all the rows of the table, turning them to objects and iterating over them. But this looks just stupid, because I have lots and lots of rectangles in my table.So I do this:SELECT sum(r.width * r.height)FROM rectangles rThis is easy, fast and uses the strengths of the database.However, it introduces duplicated logic, because I have the same calculation in my domain class also.Of course, for this example the duplication of logic is not fatal at all.However, I face the same problem with my other domain classes, which are more complex.
What are the ways to avoid duplication of logic between domain classes and SQL queries?
architecture;maintainability
As lxrec pointed out, it'll vary from codebase to codebase. Some applications will allow you to put those kind of business logic into SQL Functions and/or queries and allow you to run those anytime you need to show those values to the user.Sometimes it may seem stupid, but it's better to code for correctness than performance as a primary objective.In your sample, if you're showing the value of the area for a user in a webform, you'd have to:1) Do a post/get to the server with the values of x and y;2) The server would have to create a query to the DB Server to run the calculations;3) The DB server would make the calculations and return;4) The webserver would return the POST or GET to the user;5) Final result shown.It's stupid for simple things like the one on the sample, but it may be necessary to more complex stuff like calculating the IRR of an investment of a client in a banking system.Code for correctness. If your software is correct, but slow, you'll have chances to optimize where you need (after profiling). If that means keeping some of the business logic in the database, so be it. That's why we have refactoring techniques.If it becomes slow, or unresponsive, than you may have some optimizations to do, like violating the DRY principle, which is not a sin if you surround yourself of the proper unit testing and consistency testing.