Intermediate 30 min read

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;
    }
}

LibraryService is Module 14's Single Responsibility Principle in practice — one class focused entirely on library operations, rather than scattering insert book; calls across every place in the org that needs to add a book.

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 + ')');

Any code that needs to add a book — a Lightning component's Apex controller, a data import script, a trigger — calls LibraryService.addBook() rather than writing its own insert statement, 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];

APEX

Build the Core Classes Quiz

1. Why route every library operation through LibraryService instead of calling DML directly everywhere?

Log in to submit the quiz and save your score.

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.