Model–View–Controller (MVC) Architecture
On this page
A Small Controller and ViewMVC separates three responsibilities: the Model holds data and domain rules; the View presents results; the Controller coordinates a user request.
A Small Controller and View
First run the model and demonstration from From Diagram to Code. Ada is already enrolled in CS101, so her next request should take the duplicate path.
def enrollment_view(message):
return f"Enrollment: {message}"
def enroll_controller(student, course):
try:
enrollment = student.enroll(course)
except ValueError as error:
return enrollment_view(str(error))
return enrollment_view(f"{enrollment.student.name} -> {course.course_code}")
print(enroll_controller(ada, cs101))
grace = Student("S002", "Grace Hopper")
print(enroll_controller(grace, cs101))Output
Enrollment: Already enrolled
Enrollment: Grace Hopper -> CS101
The Controller handles the model’s ValueError. The View formats either the error or a success message; the Model still owns the enrollment rule.
Try it: change only the prefix in enrollment_view. Check that enrollment counts and grades remain unchanged.
MVC is a design pattern, not a requirement imposed by every web framework. This example needs neither a web framework nor a database.
The University Course System project now combines the model, diagrams and separation of responsibilities in one working application.