Solid Design Principles In Javascript (Part 1) — Single Responsibility Principle

SOLID Design Principles

A class should have one and only one responsibility. Which means your class should have only one job or task.

class Mailer{
constructor(mail){
this.mail = mail
this.smtpService = this.smtp_service_connection()
}
smtp_service_connection(){
// Connects to smtp service
}
send(){
this.smtpService.send(this.format_text_mail())
this.smtpService.send(this.format_html_mail())
}
format_text_mail(){
// formats to text version of mail
this.mail = "Email For You \n" + this.mail;
return this.mail;
}
format_html_mail(){
// formats to html version of mail
this.mail = `<html>
<head><title>Email For You</title></head>
<body>${this.mail}</body>
</html>`;
return this.mail;
}
}
const mailer = new Mailer("hello kwame");
mailer.send();

Better Approach

class Mailer{
constructor(mail, mailerFormats){
this.mail = mail
this.mailerFormats = mailerFormats
this.smtpService = new MailerSmtpService()
}
send(){
// Loops through mail formats and calls the send method
this.mailerFormats.forEach((formatter) => this.smtpService.send(formatter.format(this.mail)))
}
}
class MailerSmtpService{
constructor(){
this.smtp_con = this.smtp_service_connection()
}
send (mail){
this.smtp_con.send(mail)
// can easily change to be this if a service requires this implementation - smtp_con.deliver(mail)
}
smtp_service_connection(){
// Connects to smtp service
}
}
class HtmlFormatter{
constructor(){
}
format(mail){
// formats to html version of mail
mail = `<html>
<head><title>Email For You</title></head>
<body>${mail}</body>
</html>`;
return mail;
}
}
class TextFormatter{
constructor(){
}
format(mail){
// formats to text version of mail
mail = "Email For You \n" + mail;
return mail;
}
}
Design is in everything we make, but it’s also between those things. It’s a mix of craft, science, storytelling, propaganda, and philosophy.
const mailer = new Mailer("hello kwame", [new HtmlFormatter(), new TextFormatter()])
mailer.send();

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store