Handle Checkouts and Returns
By the end of this lesson, you'll be able to:
- Create a Checkout__c record and update the related Book__c when a book is checked out
- Update both records when a book is returned
- Explain why these two DML operations should happen together, not independently
Prerequisites: "Query the Catalog"
Checking out a book
public Checkout__c checkOutBook(Id bookId, String memberName) {
Book__c book = [SELECT Id, Is_Checked_Out__c FROM Book__c WHERE Id = :bookId];
book.Is_Checked_Out__c = true;
update book;
Checkout__c checkout = new Checkout__c(
Book__c = bookId,
Member_Name__c = memberName,
Checkout_Date__c = Date.today()
);
insert checkout;
return checkout;
}
Two records change together here: the Book__c itself (marked unavailable) and a new Checkout__c record (the actual borrowing event) — both are needed to keep the catalog's availability status and the borrowing history in sync with each other.
Returning a book
public void returnBook(Id checkoutId) {
Checkout__c checkout = [SELECT Id, Book__c FROM Checkout__c WHERE Id = :checkoutId];
checkout.Return_Date__c = Date.today();
update checkout;
Book__c book = [SELECT Id FROM Book__c WHERE Id = :checkout.Book__c];
book.Is_Checked_Out__c = false;
update book;
}
Returning reverses the checkout: the Checkout__c record gets its Return_Date__c filled in (closing out that borrowing event), and the related Book__c is marked available again — the relationship field (checkout.Book__c, Module 18) is what connects the two.
Why these updates need to happen together
If checkOutBook only inserted the Checkout__c but forgot to update Book__c.Is_Checked_Out__c, the catalog would incorrectly still show the book as available — a second member could "check out" a book someone already has. Keeping both records in sync inside one method (rather than trusting two separate callers to always do both) is exactly the same discipline as Module 17's validation-inside-the-class principle.
Exercise
Given an existing checkOutBook method, write a getActiveCheckouts() method returning every Checkout__c where Return_Date__c is null (still borrowed).
Show hint
WHERE Return_Date__c = null
Handle Checkouts and Returns Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Checking out or returning a book touches two records at once — this lesson keeps Book__c and Checkout__c consistent with each other using the DML patterns from Module 19.