Build the Core Classes
By the end of this lesson, you'll be able to:
- Write a LibraryService class as the entry point for library operations
- Insert a new Book__c record through the service class
- Explain why a service class sits between the UI/caller and raw DML
Prerequisites: "Design the Data Model"
A service class as the entry point
public class LibraryService {
public Book__c addBook(String title, String author, String isbn) {
Book__c book = new Book__c(
Title__c = title,
Author__c = author,
ISBN__c = isbn,
Is_Checked_Out__c = false
);
insert book;
return book;
}
}
public class LibraryService {— this is Module 14's Single Responsibility Principle in practice — one class focused entirely on library operations.public Book__c addBook(String title, String author, String isbn) {— the entry point for adding a book.Book__c book = new Book__c(— builds the record in memory.Title__c = title,— sets the title.Author__c = author,— sets the author.ISBN__c = isbn,— sets the ISBN.Is_Checked_Out__c = false— a new book starts available.);— closes the constructor call.insert book;— the onlyinsert book;this system should ever need, rather than scattered across every place in the org that needs to add a book.return book;— hands back the now-saved record, with itsIdpopulated.}— closes the method.}— closes the class.
Using the service class
LibraryService library = new LibraryService();
Book__c newBook = library.addBook('The Long Walk', 'Richard Bachman', '978-0-451-14098-6');
System.debug('Added: ' + newBook.Title__c + ' (Id: ' + newBook.Id + ')');
LibraryService library = new LibraryService();— creates the service.- (blank line)
Book__c newBook = library.addBook('The Long Walk', 'Richard Bachman', '978-0-451-14098-6');— any code that needs to add a book callsLibraryService.addBook()rather than writing its owninsertstatement.System.debug('Added: ' + newBook.Title__c + ' (Id: ' + newBook.Id + ')');— confirms it worked, keeping the actual DML logic in exactly one place.
Why not just call insert directly everywhere?
Nothing stops any code from writing insert new Book__c(...) directly. The problem is the same one from Module 17's EmployeeDirectory: if adding a book later needs a validation rule (say, rejecting a blank ISBN), that rule has to be added to every single place that inserts a Book__c — unless there's exactly one method responsible for it. LibraryService.addBook() is that one place.
Exercise
Add a getBookCount() method to LibraryService that returns the total number of Book__c records using SELECT COUNT().
Show hint
return [SELECT COUNT() FROM Book__c];
Build the Core Classes 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
This lesson builds the LibraryService class — a single, focused entry point for every library operation, starting with adding a new book to the catalog.