An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
August 17, 2022 03:15 pm GMT
Original Link: https://dev.to/jmalvarez/single-responsibility-principle-in-typescript-859
Single Responsibility Principle in TypeScript
A class should have just one reason to change.
Every class in our code should be responsible for just a single part of the application. By following this principle we reduce the complexity of our code.
If a class is responsible of multiple parts of our app, it will have to be changed frequently. Therefore, changing one part of the class increases the risk of breaking other parts of itself. The solution is to divide it into multiple classes, each one with one responsibility.
In the following bad example we can see how the Student
class has two responsibilities: managing the student data and the course data.
class Student { id: number; name: string; courseId: number; courseName: string; courseSubject: string[]; // constructor printCourseSchedule(): void { // some API call here to get the course schedule }}
Following the Single Responsibility Principle we can improve this by moving the course data to its own class.
class Student { id: number; name: string; course: Course; // constructor}class Course { id: number; name: string; subjects: string[]; // constructor printSchedule(): void { // some API call here to get the course schedule }}
Original Link: https://dev.to/jmalvarez/single-responsibility-principle-in-typescript-859
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To