Question

There is a big design flaw here, but I'm having trouble solving it:

The business need is a little involved so I'll try to keep this simple. We have a table with purchases, and a table for returns. When a return is made, we have to find match that return to the oldest purchase in the db, and record that in a "returns applied" table.

So, when I insert a Return, within that transaction, I need to apply the return to a purchase record.

As it stands now, we have a service that calls the repository for the insert. The service needs to know what the key is of that inserted record, so that it can finish the transaction by inserting an "applied" record using that key.

We're basically stuck because my understanding is that a repository should not return this kind of data. Doesn't this defeat the idea of the Repository being a collection?

What is the alternative?

CLARIFICATION:

We have a Purchase table, a Return table, and an Applied table

The applied table looks like this purchaseId returnId qtyReturned

So when a return is inserted I need the id of a purchase (decided by some business rules) and the id of the newly inserted return.

Was it helpful?

Solution

I suppose the following according to your question:

public class Purchase {

   // ReturnRepository plays the role of collaborator
   public Return returnMe(PurchaseRepository purchaseRepository, int quantity) {
       return purchaseRepository.returnPurchase(this, quantity);
   }

}


public class PurchaseRepositoryImpl implements PurchaseRepository {

    // returnd Purchase object has its id set up
    public Purchase getOldestPurchase() {
        // logic in order to get oldest purchase
    }

    public Return returnPurchase(Purchase purchase, quantity) {
        // logic in order to save a return record
        // Some ORM frameworks returns ids when a record is saved. In my case, Hibernate or NHibernate (.NET) fulfill ths requirement

        // Then purchaseId, returnId and quantity is saved in "returns applied" table
    }

}


public class PurchaseServiceImpl implements PurchaseService {

   // Injected through dependency injection
   private PurchaseRepository purchaseRepository;

   // Spring transaction boundary, for example
   // Notice returnPurchase method returns a Return object
   public Return returnPurchase(int quantity) {
       Purchase purchase = purchaseRepository.getOldestPurchase();

       return purchase.returnMe(purchaseRepository, quantity);
   }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top