Add Business Rules
By the end of this lesson, you'll be able to:
- Enforce a maximum roster size before allowing enrollment
- Prevent the same student from being enrolled twice
- Explain why business rules belong inside the class that owns the data
Prerequisites: "Model a Course Roster"
Enforcing a maximum size
public class CourseRoster {
private String courseName;
private Integer maxSize;
private List<Student> enrolledStudents = new List<Student>();
public CourseRoster(String courseName, Integer maxSize) {
this.courseName = courseName;
this.maxSize = maxSize;
}
public Boolean enroll(Student student) {
if (enrolledStudents.size() >= maxSize) {
System.debug('Roster full — cannot enroll ' + student.getName());
return false;
}
enrolledStudents.add(student);
return true;
}
}
enroll() now returns a Boolean reporting whether it actually succeeded — this is Module 6's if-statement pattern doing real business work, and it means calling code can react to a full roster instead of blindly assuming every enrollment worked.
Preventing duplicate enrollment
public Boolean enroll(Student student) {
for (Student existing : enrolledStudents) {
if (existing.getStudentId() == student.getStudentId()) {
System.debug(student.getName() + ' is already enrolled.');
return false;
}
}
if (enrolledStudents.size() >= maxSize) {
System.debug('Roster full — cannot enroll ' + student.getName());
return false;
}
enrolledStudents.add(student);
return true;
}
Checking for an existing enrollment before checking capacity means a genuinely duplicate enrollment gets a clear, specific message rather than a generic "roster full" — the order these checks run in actually matters for how helpful the feedback is.
Why these rules live inside CourseRoster
It would be possible to write these checks as separate, standalone code wherever enroll gets called instead — but then every caller would need to remember to repeat them, and any caller that forgot would silently create an invalid roster. Putting the rules inside CourseRoster.enroll() itself (the same encapsulation principle from Module 11) means the rule is enforced everywhere, automatically, with no way to bypass it.
Exercise
Add a getRemainingSeats() method to CourseRoster returning maxSize minus the current enrollment count.
Show hint
return maxSize - enrolledStudents.size();
Add Business Rules 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
Real rosters have real limits — this lesson adds business rules (a maximum size, no duplicate enrollments) directly inside CourseRoster, where the data they protect actually lives.