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

推荐订阅源

G
GRAHAM CLULEY
S
Security @ Cisco Blogs
P
Proofpoint News Feed
Cisco Talos Blog
Cisco Talos Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tor Project blog
WordPress大学
WordPress大学
Project Zero
Project Zero
S
Schneier on Security
P
Proofpoint News Feed
小众软件
小众软件
P
Privacy International News Feed
美团技术团队
L
LangChain Blog
Know Your Adversary
Know Your Adversary
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Register - Security
The Register - Security
N
Netflix TechBlog - Medium
Microsoft Security Blog
Microsoft Security Blog
Engineering at Meta
Engineering at Meta
I
InfoQ
量子位
Vercel News
Vercel News
博客园 - 三生石上(FineUI控件)
Spread Privacy
Spread Privacy
D
DataBreaches.Net
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
U
Unit 42
P
Privacy & Cybersecurity Law Blog
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
Latest news
Latest news
K
Kaspersky official blog
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
Simon Willison's Weblog
Simon Willison's Weblog
云风的 BLOG
云风的 BLOG
S
Securelist
AWS News Blog
AWS News Blog
F
Fortinet All Blogs
T
Threat Research - Cisco Blogs
Stack Overflow Blog
Stack Overflow Blog
Scott Helme
Scott Helme
Help Net Security
Help Net Security
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Tenable Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Programming to Interface Vs to Implementation
Dmitri Pavlutin · 2022-01-24 · via Dmitri Pavlutin Blog

You've written some code, tested, and shipped to production. Then you never have to modify that code again. Wouldn't that be great?

But putting the dreams aside... you have to modify, even multiple times, the code that has been written. And this in my opinion is one of the big challenges in software development: updating the already written code.

If you haven't taken the time, in advance, to think about the possible ways your code can change, you're quickly going to start to have problems with rigid and fragile code.

In this post, I'm going to discuss a software design principle that advises to program to an interface rather than an implementation to help you write code can be modified easier in the future.

Table of Contents

  • 1. The list renderer
  • 2. Programming to an implementation
    • 2.1 Changing implementations
  • 3. Programming to an interface
    • 3.1 Programming to an interface in practice
  • 4. Benefits vs increased complexity
  • 5. Conclusion

1. The list renderer

A good way to understand the benefits of software design principles is to follow an example and demonstrate visible benefits.

First, I'm going to show you an implementation that's not adapted to change. Then, by applying the program to an interface principle, redesign the component and demonstrate the advantages of the new design.

For example, you have the task of implementing a class ListRenderer. The class has just one method listRender.render(names), which renders an array of names into an unordered HTML list.

One class

Here's how you could implement the ListRenderer class:


class ListRenderer {

render(names: string[]): string {

let html = '<ul>';

for (const name of names) {

html += `<li>${name}</li>`;

}

html += '</ul>';

return html;

}

}


And now let's use the list renderer to render some names:


const renderer = new ListRenderer();

renderer.render(['Joker', 'Catwoman', 'Batman']);

// =>

// <ul>

// <li>Joker</li>

// <li>Catwoman</li>

// <li>Batman</li>

// </ul>


Open the demo.

The above implementation is a good solution if you want to simply render a list of names. But what if you need to change further this code, for example add sorting functionality?

2. Programming to an implementation

As I mentioned in the post introduction, there's a good chance that the already written code will have to be modified when new requirements arise.

Let's say there's a new requirement to also sort alphabetically the rendered names.

You can implement this requirement by creating a new sorter class, for example, SortAlphabetically:


class SortAlphabetically {

sort(strings: string[]): string[] {

return [...strings].sort((s1, s2) => s1.localeCompare(s2))

}

}


where s1.localCompare(s2) is a string method that compare whether s1 comes alphabetically before or after s2.

Then integrate SortAlphabetically into the ListRender, enabling the sorting of the names before rendering:


class ListRenderer {

sorter: SortAlphabetically;

constructor() {

this.sorter = new SortAlphabetically();

}

render(names: string[]): string {

const sortedNames = this.sorter.sort(names)

let html = '<ul>';

for (const name of sortedNames) {

html += `<li>${name}</li>`;

}

html += '</ul>';

return html;

}

}


Now with the new sorting logic integrated, the list renders the names sorted alphabetically:


const renderer = new ListRenderer();

renderer.render(['Joker', 'Catwoman', 'Batman']);

// =>

// <ul>

// <li>Bane</li>

// <li>Catwoman</li>

// <li>Joker</li>

// </ul>


Open the demo.

Now let's look closer at the sorter instantiation line:


this.sorter = new SortAlphabetically();


This is programming to implementation because ListRenderer uses a concrete implementation of the sorter, and exactly SortAlphabetically implementation.

Depending on one implementation

Is programming to an implementation a problem? The answer depends on how your code will change in the future.

If you are sure that the list renderer will sort the names alphabetically only — and this requirement most likely won't change in the future — then the programming to the concrete sorting implementation is good.

2.1 Changing implementations

But you might have difficulties with the programming to implementation if the sorting implementation might change in the future, or if you need different sorting depending on runtime values.

For example, you might want to sort the names alphabetically in ascending or descending order depending on the user's choice.

When using programming to implementation you will start bloating your main component with the sorting implementation details. This quickly makes your code hard to reason about and hard to change:


class ListRenderer {

sorter: SortAlphabetically | SortAlphabeticallyDescending;

constructor(ascending: boolean) {

this.sorter = ascending ?

new SortAlphabetically() :

new SortAlphabeticallyDescending();

}

render(names: string[]): string {

// ...

}

}


In the example above ListRenderer can sort the names ascending or descending. What kind of sorting is used depends on the ascending parameter.

Depending on 2 implementations

You can see how complex becomes ListRenderer — it becomes bloated with the sorting implementation details.

What if later you'd like to add more sorting implementations? By referencing new sorting implementations in ListRenderer makes the class over-complicated with details it doesn't have to know.

Such design breaks 2 important software design principles.

Firstly, the design breaks the Single Responsibility Principle. The ListRenderer should be solely responsible to render the names, but now additionally it is also responsible to instantiate and select its right sorting implementation.

Secondly, adding new ways of sorting by directly modifying the ListRenderer breaks the Open/Closed Principle.

How to design the changeable dependency implementations? Welcome programming to an interface!

3. Programming to an interface

If you want to make ListRenderer more extensible and decoupled from a concrete sorting implementation, then you need to use the programming to an interface approach.

Here's what you need to do to improve the design of the renderer with different sorting mechanisms:

  1. Define the interface (or the abstract class) Sorter that represent the sorting behavior
  2. Make the ListRender depend on the Sorter interface, rather than the concrete implementation (SortAlphabetically and SortAlphabeticallyDescending)
  3. Make the concrete sorting implementations (SortAlphabetically and SortAlphabeticallyDescending) implement the Sorter interface
  4. Compose a ListRenderer instance with the right sorting implementation: new ListRenderer(new SortAlphabetically()) or new ListRenderer(new SortAlphabeticallyDescending())

The main idea of programming to an interface is to introduce a stable construction — an interface (or abstract class) — and depend on it. You also extract the logic of instantiating and choosing the implementation out of the main class.

Depending on an interface

3.1 Programming to an interface in practice

Ok, let's see how to put programming to an interface into practice to improve the design of list renderer.

  1. Defining the interface Sorter should be relatively easy:


interface Sorter {

sort(strings: string[]): string[]

}


Sorter interface contains just one method sort() that sorts an array of strings. The interface isn't concerned about how the sort() method works: just that it accepts an array of strings and should return an array of sorted strings.

  1. Making the ListRender use the Sorter interface is easy too. Just remove the references to the concrete implementations and use the Sorter interface solely:


class ListRenderer {

sorter: Sorter;

constructor(sorter: Sorter) {

this.sorter = sorter;

}

render(names: string[]): string {

const sortedNames = this.sorter.sort(names)

let html = '<ul>';

for (const name of sortedNames) {

html += `<li>${name}</li>`;

}

html += '</ul>';

return html;

}

}


Now ListRenderer doesn't depend on a concrete implementation of the sorting. That makes the class easy to reason about and decoupled from sorting logic. It depends on a very stable thing: the Sorter interface.

The presence of sorter: Sorter in the ListRenderer is what is called programming to an interface.

  1. Finally, making the concrete sorting class implement the Sorter interface is relatively easy too:


class SortAlphabetically implements Sorter {

sort(strings: string[]): string[] {

return [...strings].sort((s1, s2) => s1.localeCompare(s2))

}

}



class SortAlphabeticallyDescending implements Sorter {

sort(strings: string[]): string[] {

return [...strings].sort((s1, s2) => s2.localeCompare(s1))

}

}


4. Benefits vs increased complexity

You might say that programming to an interface requires more moving parts than coding to an implementation. You're right!

The biggest benefit, as you might see already, is the ListRenderer class using an abstract interface Sorter.

As such ListRenderer is decoupled from any concrete implementations of sortings: SortAlphabetically or SortAlphabeticallyDescending.

Now you can supply different implementations of sorting. In one case you can use sorting alphabetically ascending:


const names = ['Joker', 'Catwoman', 'Batman'];

const rendererAscending = new ListRenderer(

new SortAlphabetically()

);

rendererAscending.render(names);

// =>

// <ul>

// <li>Batman</li>

// <li>Catwoman</li>

// <li>Joker</li>

// </ul>


Open the demo.

In another case you can easily compose the ListRenderer to sort the names descending, without modifying the source code of ListRenderer:


const names = ['Joker', 'Catwoman', 'Batman'];

const rendererDescending = new ListRenderer(

new SortAlphabeticallyDescending()

);

rendererDescending.render(names);

// =>

// <ul>

// <li>Joker</li>

// <li>Catwoman</li>

// <li>Batman</li>

// </ul>


Open the demo.

But you can also choose the concrete sorting depending on a runtime value:


const sorting =

someRuntimeBoolean ?

new SortAlphabetically() :

new SortAlphabeticallyDescending();

const renderer = new ListRenderer(

sorting

);

// ...


5. Conclusion

Programming to an interface is a useful principle to design a dependency that can change in time or different dependency implementations can be selected by a runtime value.

Programming to an interface usually requires the main class (e.g. ListRenderer) to depend on an interface (e.g. Sorter), and the concrete implementations (e.g. SortAlphabetically and SortAlphabeticallyDescending) to implement that interface.

The client of the main class (e.g. ListRenderer) can supply any dependency implementation it needs at hand, without modifying the source code of the main class (e.g. ListRenderer).

Note that programming to an interface comes with the price of increased complexity. Using it must be a wise and deliberate choice.

However, if you're sure that a certain part of your code won't change, then programming to an implementation is a good and cheap choice!

For example, if the ListRenderer will always sort the names alphabetically in ascending order: then stop at the design presented at the beginning of section 2. Do not add unnecessary complexity.