Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active May 6, 2023 08:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save branneman/584f31eb298751ca65b14220e7bb55ce to your computer and use it in GitHub Desktop.
Save branneman/584f31eb298751ca65b14220e7bb55ce to your computer and use it in GitHub Desktop.
JavaScript examples: No coupling, Loose coupling, Tight coupling
{
// Tight coupling from A to B => A needs B to be defined, callable and adhere to an interface
// No coupling from B to A => B does not need A in any way (pure fn)
function a() {
b()
}
function b() {}
}
{
// No coupling from A to B => A and B work independently,
// although there a chance of naming collision in `store`
// Tight coupling from A to store => Direct reference to `store`, mutates original
// Tight coupling from B to store => Direct reference to `store`, mutates original
const store = {}
function a() {
store.foo = 'x'
}
function b() {
store.bar = 'y'
}
}
{
// Loose coupling between A and B => A and B both operate on the numeric `counter` property,
// although they will not error when it does not exist
// Tight coupling from A to store => Direct reference to `store`, mutates original
// Tight coupling from B to store => Direct reference to `store`, mutates original
const store = {}
function a() {
store.counter = (store.counter || 0) + 1
}
function b() {
store.counter = (store.counter || 0) + 10
}
}
{
// No coupling between A and B => A and B work independently,
// although there a chance of naming collision in `store`
// Loose coupling from A to store => Because DI and immutability (pure fn)
// Loose coupling from B to store => Because DI and immutability (pure fn)
function a(store) {
return Object.assign({}, store, { foo: 'x' })
}
function b(store) {
return Object.assign({}, store, { bar: 'y' })
}
const store0 = {}
const store1 = a(store0)
const store2 = b(store1)
}
/**
* Returns a new list or string with the elements or characters in reverse
* Tight Coupled to `_isString`
*/
const reverse = (list) => {
return _isString(list)
? list.split('').reverse().join('')
: Array.prototype.slice.call(list, 0).reverse()
}
// util/types.js
const _isString = (x) => {
return Object.prototype.toString.call(x) === '[object String]'
}
// Loose Coupling to connector, via DI
class ControllerB {
indexPage(db: DbConnector) {
db.query('SELECT ...')
}
}
interface DbConnector {
query(s: String): any
}
class PostgresConnector implements DbConnector {
query() {
/* ... */
}
}
// Tight Coupling to MySQLConnector
class ControllerA {
indexPage() {
const db = new MySQLConnector(env.creds)
db.query('SELECT ...')
}
}
class MySQLConnector {
constructor() {
/* ... */
}
query() {
/* ... */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment