19

I'm a little bit confused about an example found on the web - spring & hibernate (point 4. Model & BO & DAO). There are Model, DAO and BO classes (+ DAO and BO interfaces). What I do not clearly understand is why DAO and BO are separated into different classes if they share exactly the same functionalities (only difference is that BO has a DAO setter).

The author explains only, that the pattern:

is useful to identify the layer clearly to avoid mess up the project structure

but it seems over-engineered to me (at least in this case). I know this example is very simple, but what this class separation could be useful for? Could someone provide an example?

ducin
  • 25,621
  • 41
  • 157
  • 256
  • 2
    I imange one's BOs would _hold_ data whereas one's DAOs would _retrieve_ data. – Boris the Spider Feb 17 '13 at 17:16
  • 2
    If DAOs were not separated it would be difficult for BOs (services) to reuse the DAOs. There are other advantages too, like if you change the underlying DB or ORM framework the BOs reamin unaffected since only the implementation part of the DAO needs change. – techuser soma Feb 17 '13 at 18:13

1 Answers1

35

What they call a BO seems to be a business service. A DAO's job is to contain the persistence-related code: inserting, updating, querying the database.

The services demarcate transactions, contain business logic, and usually use one or several DAOs to implement this logic. For some use cases, the service just delegates to the DAO. For others, it calls several methods of one or several DAOs.

The classical example is a money transfer service:

public void transferMoney(Long sourceAccountId, Long targetAccountId, BigDecimal amount) {
    Account source = accountDAO.getById(sourceAccountId);
    Account target = accountDAO.getById(targetAccountId);
    if (source.getBalance().compareTo(amount) < 0) {
        throw new NotEnoughMoneyException();
    }
    source.decrementBalance(amount);
    target.incrementBalance(amount);
    auditDAO.insertTransaction(sourceAccountId, targetAccountId, amount);
    // other business logic
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255