惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News: Ask HN
Hacker News: Ask HN
C
Cisco Blogs
The Hacker News
The Hacker News
T
Tor Project blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
A
Arctic Wolf
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Register - Security
The Register - Security
云风的 BLOG
云风的 BLOG
Simon Willison's Weblog
Simon Willison's Weblog
P
Palo Alto Networks Blog
Vercel News
Vercel News
C
CERT Recently Published Vulnerability Notes
I
InfoQ
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
M
MIT News - Artificial intelligence
I
Intezer
aimingoo的专栏
aimingoo的专栏
U
Unit 42
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 热门话题
Microsoft Security Blog
Microsoft Security Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyberwarzone
Cyberwarzone
P
Proofpoint News Feed
P
Proofpoint News Feed
B
Blog
T
Threat Research - Cisco Blogs
博客园 - 叶小钗
Recorded Future
Recorded Future
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Know Your Adversary
Know Your Adversary
Engineering at Meta
Engineering at Meta
G
Google Developers Blog
PCI Perspectives
PCI Perspectives
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
Application and Cybersecurity Blog
Application and Cybersecurity Blog
MyScale Blog
MyScale Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
Schneier on Security
Schneier on Security
N
News | PayPal Newsroom
C
Cybersecurity and Infrastructure Security Agency CISA
H
Help Net Security
博客园 - 聂微东
H
Hackread – Cybersecurity News, Data Breaches, AI and More
G
GRAHAM CLULEY

Yusuf Aytas

When Code Is Cheap, Does Quality Still Matter? Why Crouching Tiger, Hidden Dragon Is a Masterpiece Why We Ignore Advice The Mirror Is Part of the Machine When Too Many Maps Overlap on One Person The Work Runs on Different Maps Your Work Introduces You Trial By Fire The Dude Why Headcount Math Lies Capacity Is the Roadmap The Roadmap Is Not the System Torres del Paine W Trek Escaping Status Theater Incentives Drive Everything Scaling Culture Without Dilution What Good Looks Like Why Airport Security Feels Random Why Politics Appear How to Work with Me The Janus Protocol Multi-Horizon Delivery Framework What Good Execution Looks Like Managing Your Manager Why Kingdom of Heaven’s Director’s Cut Is Better AI Broke Interviews Most of What We Call Progress Managers Have Been Vibe Coding All Along Stop Wasting Brainpower Why Over-Engineering Happens Prisoner's Dilemma Climbing No More The Weekly Win Mevlana Candy Brewing Turkish Tea Onboarding Your Engineering Manager Technical Deep Dives Yapay Zekâ Çağında Bilgisayar Mühendisliği Building Remote Teams From Idea to Launch in 2 Weeks Reflecting on Software Engineering Handbook Representing the Business New Manager Survival Guide Take Self Reviews Seriously Chasing Real Respect The Invisible Difference Learning the Johari Window Management is a Lonely Place Simple Task Management AI Balance in Work PIP Manager Insights Engineering Manager Interview Preparation Work-Life Balance as a Manager Bridging the Management Disconnect Tech Hiring Bubble Bursts Traits for EMs Simple Acts of Recognition Matter The Question I Ask Every New Report The Reality of an Employer's Market Bridging Ideals and Reality Hiring Red Flags Why The Godfather Is So Damn Good Subteam Tenets No Fluff Please Losing a Top Performer Balancing Act of Reliability Building Trust in Engineering Teams Ideal Number of Direct Reports Overriding a People Leader’s Decision From Misperception to Promotion Perception vs Perspective Setting Goals From Engineer to Manager Getting Delegation Right Interviewing Your Future Boss Celebrating Our Book in Iceland Operational Skills Needed On Writing Software Engineering Handbook Charlie Munger Quotes Working with Dependencies From Las Vegas to Canyons Navigating Layoffs Handling Competitive Dynamics A Weekend Getaway to Malta Engineering Health Essentials Should Dev Managers Code? Confronting the Life on Pause Winning Eleven Kindness is A Choice Bireysel Katılımcılar ve Yöneticiler Leading from Where You Are The Subtle Art of Listening Coding in Leadership The Power of Consistency The Making of a Leader The Path to Leadership Embracing TikTok Talent Sourcing Journey Leading Self Managing Teams Cracking Coding Bottlenecks
Achieving Abstraction In JavaScript
Yusuf Aytas · 2013-05-17 · via Yusuf Aytas

Published · 5 min read

In computer science, abstraction is to hide certain details and only show the essential features of the object. Abstraction tries to reduce and factor out details so that the developer can focus on a few concepts at a time. This approach improves understandability as well as maintainability of the code. While abstraction is well understood and well applied in languages like Java, C++,  this approach is not discussed much for JavaScript. In this post, we will try to give some insight for abstraction of JavaScript.

First of all, there is not built in support for traditional abstraction in JavaScript. At least, there are not any types like interfaces and abstract classes. Developers are in general does not care for abstraction. Although, ignoring abstraction does not cause any problems while writing small piece of code, it can be relatively difficult when you are dealing with a large scale application. On the other hand, abstraction provides ways of dealing with cross-cutting concerns and enables us to avoid tightly coupled code. There is a good saying about abstraction "Program to an interface, not an implementation." from Design Patterns book. To deal with complex applications one should use interfaces because using same interface you can change implementation whenever you want without much effort. For those reasons, we should have abstraction in JavaScript, too.

For abstraction, one can use interfaces and abstract classes but JavaScript does not have such features. We can alternatively define interfaces using prototypes. Let's see how we define an interface in JavaScript.

//ItemRepo interface
var ItemRepo = {
   addItem : function(item){},
   removeItem : function(id){},
   getItem:function(id){}
};

We have just defined which methods ItemRepo has. We will now define two implementations for ItemRepo : the first one is to save and retrieve data by ajax and the second one is to save and retrieve data from cookie. Let's see how we implement ItemRepo interface.

var ItemRepoAjax = function(url){
   this.url = url;
};
var ItemRepoCookie = function(){};
//Extend the ItemRepo for Ajax
ItemRepoAjax.prototype = Object.create(ItemRepo);
//Extend the ItemRepo for Cookie
ItemRepoCookie.prototype = Object.create(ItemRepo);
ItemRepoAjax.prototype.addItem = function(item){
   //actual add item code
};
ItemRepoCookie.prototype.addItem = function(item){
   //actual add item code
};

As we have defined our implementations for ItemRepo, Let's create a new class that will make use of ItemRepo.

var ItemController = function(itemRepo){
   this.itemRepo = itemRepo;
};
ItemController.prototype.add = function(item){
   itemRepo.addItem(item);
};

As long as we have two implementation for ItemRepo, we can easily switch our repository between one another to save and retrieve data. This will improve maintainability and testability of the code. We could easily mock the itemRepo object and test the rest with the mock. Moreover, we could change our way of saving and retrieving data without changing the rest of the code. Let's make use of one of the ItemController and ItemRepo.

var itemRepo = new ItemRepoAjax("url");
var itemController = new ItemController(itemRepo);
itemController.add({item:"myItem"});

As we have implemented our controller class, we may want to log or profile methods for this class. We can do that by extending ItemController and injecting a logger into it. Let's see how do that.

var Logger = {
   log : function(log){}
}
var ConsoleLogger = function() {};
ConsoleLogger.prototype = Object.create(Logger);
ConsoleLogger.prototype.log = function(log) {
   //actual logging code
}
// Define new Controller
var LoggingItemController = function(itemRepo, logger){
   this.itemRepo = itemRepo;
   this.logger = logger;
}
LoggingItemController.prototype = Object.create(ItemController);
LoggingItemController.prototype.add = function(item) {
   this.logger.log("start");
   this.itemRepo.addItem(item);
   this.logger.log("stop");
};
var consoleLogger = new ConsoleLogger();
var itemRepo = new ItemRepoCookie();
var loggingItemController = 
   new LoggingItemController(itemRepo, consoleLogger);
loggingItemController.add("item");

Moreover, we can apply classic patterns easily by using interface definitions. To make it clear, let's see how we define Factory pattern in JavaScript.

var ItemRepoFactory = {
   getItemRepo : function(type) {}
};
var ConcreteItemRepoFactory = function() {};
ConcreteItemRepoFactory.prototype = Object.create(ItemRepoFactory);
ConcreteItemRepoFactory.prototype.getItemRepo = function(type) {
   if (type === "ajax") {
      return new ItemRepoAjax("url");
   }
   return new ItemRepoCookie();
};

Using interfaces in JavaScript not only increases maintainability, it also increases testability. We can easily write mock classes to test the code. Let's see how we test the code with mock objects.

var ItemRepoMock = function(mockItem){
   this.mockItem = mockItem;
};
//Extend the ItemRepo for Ajax
ItemRepoMock.prototype = Object.create(ItemRepo);
ItemRepoMock.prototype.getItem = function(id){
   return this.mockItem;
}
function testGetItem(){
   var mockItem =  "mock";
   var mockItemRepo = new ItemRepoMock(mockItem);
   var itemController = new ItemController(mockItemRepo);
   //An equal method is needed.
   equal(itemController.getItem("id"), mockItem);
}

By defining those interfaces, one can reuse objects create by using dependency injection pattern. There are libraries that supports dependency injection like wire, but we can create a manual dependency injection on start of our application by defining every variable. Having defined dependencies at the beginning, we could easily change type of itemRepo or logger without touching any code but the configuration for dependencies.

In consequence, JavaScript is a weakly typed language and does not have classical support for abstraction. We have tried to achieve abstraction in JavaScript by defining interfaces and using them. Nevertheless, interfaces do not affect our code at all. They are nothing more than a way of documenting code for human beings. All the examples we have shown above would work exactly the same even if we completely remove the interfaces. However, it is about making roles explicit. This increases readability, understandability and maintainability of the code.