Search⌘ K
AI Features

Solution: The Single Responsibility Principle

Understand how to apply the Single Responsibility Principle by refactoring a Python class to separate data handling and computation. Learn to divide responsibilities between classes to improve code readability and maintainability.

We'll cover the following...

Solution overview

We have refactored the Student class in the following manner:

Python 3.10.4
from data import students_data
from classes import Student, SemesterResult, CGPACalculator
if __name__ == "__main__":
# Creating a list of students using students_data
students = []
for student_item in students_data:
# Creating a student instance
student = Student(student_item['ID'], student_item['name'], student_item['major'])
# Appending student results
for result_item in student_item['results']:
# Creating a result instance and adding to student's results
result = SemesterResult(result_item['number'], result_item['gpa'], result_item['ch'])
student.add_semester_result(result)
students.append(student)
# Calculating students' CGPAs
for student in students:
print(
f"student ID: {student.get_id()},",
"CGPA: %0.2f" % (CGPACalculator.calculate(student.get_results()))
)

Code explanation

Our class Student originally handled two different ...