tanyehzheng
tanyehzheng

Reputation: 2221

Where should I put the following method?

I have 2 tables with the relationship:

Purchase 1:m Payment

I have a DAO class for each table. Now I want to implement a function

List<Payment> findPaymentsByPurchaseId(int purchaseId)

To make the API feels more intuitive, should I put this function in

  1. PurchaseDAO to indicate "if I want to find anything based on Purchase information, I just call a function in PurchaseDAO"
  2. PaymentDAO to indicate "if I want to find Payment information, I just call a function in PaymentDAO"

Which one do you feel more intuitive?

Upvotes: 0

Views: 85

Answers (3)

Dave Newton
Dave Newton

Reputation: 160171

It could go multiple places.

In a purchase DAO, you'd want:

List<Payment> getPaymentsFor(Purchase) // or find..., or findByPurchase, or...

In a payment DAO, you'd want:

Purchase getPurchaseFor(Payment)

(Whether it's an ID or the object is more philosophical than technical; use whatever works for you. Exposing an ID might be considered a leaky abstraction, although it's more a cognitive one, since having a PK doesn't mean it must be a DB PK, it could just be a GUID.)

Upvotes: 1

SuprF1y
SuprF1y

Reputation: 100

A Purchase'knows' about its payments - so ask it. aka 'don't call me I'll call you'

Personally I create a class hierarchy like

Purchases
Purchase 
PurchaseDAO

Payments 
Payment
PaymentDAO


Purchases purchases = Purchases.find(criteria); 
// user selects one of the purchases (say)
Purchase = purchase.load(purchaseId);
// calls 
PurchaseDAO.load(purchaseId);
// which calls
Payments payment = Purchase.findPayments(); 
// calls 
Payments.find(purchaseId);
// calls 
PaymentDAO.find(purchaseId);

At the end you'll have a Purchase object which you can interrogate about its payments. If there are likely to be many payments against a purchase you can defer loading the payments until needed.

This seems like extra work (and is) but it allows a clean seperation of business and persistence logic and I find pays back the small investment of creating the extra classes.

Upvotes: 0

Phil
Phil

Reputation: 164731

I'd put it in PaymentDAO as it's returning payments but I'd also make it more generic

List<Payment> findByPurchase(Purchase purchase)

Upvotes: 3

Related Questions