SOLID Principle In Typescript

Table of contents

No heading

No headings in the article.

S: Single Responsibility Principle A class or function should have one and the only reason to change. Each class should do one thing & do it well. Instead of thinking that we should split code because it would look cleaner in a single file, we split code up based on the users' social structure. Because that's what dictates change. Few things to note:

Don't put functions in the same class that change for various causes. Think responsibilities (reason to change) regarding the user who will use it. The class should be low coupling & high cohesive. if we had a Technical department and a Finance department in an enterprise application that calculates salary, working hours, and saves records to DB.We'd better make sure we've split up (or abstracted) the operations most likely to change for each department in an enterprise application that calculates salary, working hours, and saves records to DB

class Employee { public calculateSalary (): number { // code...} public hoursWorked (): number { // code..} public storeToDB (): any { // code.. } } //Here's an SRP violation:

All functions have the same logic, changing a function for one department will affect other departments too. If the head of Finance changes the logic of their department, it will affect the technical department, or if we try to handle it in the same class, it leads to a bad nested if-else or switch statement.

abstract class Employee { abstract calculateSalary (): number; abstract hoursWorked (): number; protected storeToDB ():any { } } // we are forcing the developer to write their own implementation for different class by abstract methods class Technical extends Employee { calculateSalary (): number { ….code } hoursWorked (): number {...code } } class Finance extends Employee { calculateSalary (): number {...code} hoursWorked (): number {..code} }

Still confused about what should go inside a class: start thinking in terms of who is going to use it (roles & user).