Created
December 8, 2023 16:19
-
-
Save suhailgupta03/841c6ac1ee62af90ca44d5d4196c5b4f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Dependency Inversion Principle (DIP): | |
* High-level modules should not depend directly on low-level modules, | |
* but both should depend on abstractions. Additionally, these abstractions | |
* should not depend on details; rather, details should depend on abstractions. | |
*/ | |
// Bad: High-level module depends on the low-level module's details. | |
class EmailClient { | |
sendEmail() { | |
const smtpServer = new SmtpServer(); | |
smtpServer.connect(); | |
// Send email logic... | |
} | |
} | |
class SmtpServer { | |
connect() { | |
// Connect to SMTP server | |
} | |
} | |
class SmtpServerV2 { | |
connect() { | |
// Connect to SMTP server | |
} | |
} | |
// Good: Both high-level and low-level modules depend on abstractions. | |
class IEmailServer { | |
connect() {} | |
} | |
class SmtpServer extends IEmailServer { | |
connect() { | |
// Connect to SMTP server | |
} | |
} | |
class EmailClient { | |
constructor(emailServer) { | |
this.emailServer = emailServer; | |
} | |
sendEmail() { | |
this.emailServer.connect(); | |
// Send email logic... | |
} | |
} | |
// Usage | |
const smtpServer = new SmtpServer(); | |
const v2 = new SmtpServerV2(); | |
const emailClient = new EmailClient(smtpServer); | |
emailClient.sendEmail(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment