Skip to content

Instantly share code, notes, and snippets.

@r3code
Created April 6, 2018 07:06
Show Gist options
  • Save r3code/96c4c81135217c95397f07fb65e0c771 to your computer and use it in GitHub Desktop.
Save r3code/96c4c81135217c95397f07fb65e0c771 to your computer and use it in GitHub Desktop.
Making our JS code more clear (splitiing the code)
// # Making our JS code more clear
// Based on https://codepen.io/dongguangming/pen/bNjzzw
// --------------------------------------------------------------
//
// ## 1. Initial code. Bad practice.
//
// * Mixed IO and data processing all in one place.
// * It is not self-documenting, as it is not clear at-a-glance what is happening inside it.
// * It can not be easily unit tested as it has side-effects (e.g. API calls) mixed in with its output logic.
//
function findSpecialMove(character) {
var url = 'https://movies.com/sf2';
url += '?character=' + character;
var response = $.ajax({
url: url,
async: false,
dataType: 'json'
});
var data = response.responseJSON;
if ('error' in data) throw 'Invalid SF2 character ID';
return data.special;
}
// --------------------------------------------------------------
//
// ## 2. Incomplete refactor
//
// Here we decouple our I/O from our logic by moving the API call into a separate method,
// in the name of hiding complexity.
// But the logic for URL creation and data parsing remains tightly coupled.
// It can not be tested without triggering the I/O.
//
function findSpecialMove(character) {
var url = 'https://movies.com/sf2';
url += '?character=' + character;
var data = _getAPIData(url);
if ('error' in data) throw 'Invalid SF2 character ID';
return data.special;
}
function _getAPIData(url) {
var response = $.ajax({
url: url,
async: false,
dataType: 'json'
});
var data = response.responseJSON;
return data;
}
// --------------------------------------------------------------
//
// ## 3. Final refactor (clean)
//
// * Main findSpecialMove function is now very readable, as it contains only simple calls to other functions.
// * It is clear how it works internally.
// * URL creation and data processing logic is abstracted away.
// * Function names describe what their function code is doing.
// * Each of these functions has a single input and output.
// * They can be easily tested in isolation without depending on I/O or other parts of the app.
function findSpecialMove(character) {
var url = _buildURL(character);
var data = _getAPIData(url);
return _pluckSpecialMove(data);
}
function _buildURL(character) {
var url = 'https://movies.com/sf2';
url += '?character=' + character;
return url;
}
function _getAPIData(url) {
var response = $.ajax({
url: url,
async: false,
dataType: 'json'
});
var data = response.responseJSON;
return data;
}
function _pluckSpecialMove(data) {
if ('error' in data) throw 'Invalid SF2 character ID';
return data.special;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment