Last active
January 3, 2022 15:03
-
-
Save peterheard01/00763188443df1229423 to your computer and use it in GitHub Desktop.
An example of coupling and decoupling in Javascript
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
//this type of coupling happens when you expose the internals object A to object B | |
//in this example we are accessing a method and assigning a property. | |
//this type of coupling happens when one module asks a question of another module | |
//if Person changes how it represents 'hasHobby' it breaks the coupled version in | |
//2 places | |
//by using a 3rd object to hold that information we only break the code in 1 | |
//place if we ever change how the Person represents hwo they have a hobby | |
//coupled | |
function main(){ | |
var hobby = 'rowing'; | |
var person1 = new Person(); | |
var person2 = new Person(); | |
//update the person1 hobby | |
if(person1.needsHobby()){ | |
person1.hobby = hobby; | |
} | |
//update person2 hobby | |
if(person2.needsHobby()){ | |
person2.hobby = hobby; | |
} | |
} | |
//decoupled/ioc | |
function main(){ | |
var hobby = 'rowing'; | |
var person1 = new Person(); | |
var person2 = new Person(); | |
var hobbyUpdater = new HobbyUpdater(); | |
hobbyUpdater.update(person1,hobby); | |
hobbyUpdater.update(person2,hobby); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment