Skip to content

Instantly share code, notes, and snippets.

@peterheard01
Last active January 3, 2022 15:03
Show Gist options
  • Save peterheard01/00763188443df1229423 to your computer and use it in GitHub Desktop.
Save peterheard01/00763188443df1229423 to your computer and use it in GitHub Desktop.
An example of coupling and decoupling in Javascript
//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