Skip to content

Instantly share code, notes, and snippets.

@SimplGy
Created April 3, 2012 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimplGy/2293129 to your computer and use it in GitHub Desktop.
Save SimplGy/2293129 to your computer and use it in GitHub Desktop.
Comparison of two ways to check for bad data in a method
//------------------ Option A: Use if else to avoid execution of bad data
// panelData = {
// title: "a title for the panel (optional)"
// subtitle: "subtitle for the panel (optional)"
// contents: "panel contents (required)"
// }
_addPanel = function (panelData) {
var $panel
, panelPos
;
// Verify the integrity of the panelData
if (!panelData || !panelData.contents) {
log.error(_me + ': can\'t add a panel without a data object that has .contents');
} else {
// Add the panel to the dom and track it in memory
$panel = $(tmpl(panelTemplate, panelData));
$panel.css('width', _panelWidth);
_configureRandomPanel($panel.find('.panel'));
_panels.push($panel);
_$panelBox.append($panel);
// Record the panel position in memory
panelPos = _calculatePanelPos(_panels.length - 1);
_panelPositions.push(panelPos);
}
};
//------------------ Option B: Use return to avoid execution for bad data
// panelData = {
// title: "a title for the panel (optional)"
// subtitle: "subtitle for the panel (optional)"
// contents: "panel contents (required)"
// }
_addPanel = function (panelData) {
var $panel
, panelPos
;
// Verify the integrity of the panelData
if (!panelData || !panelData.contents) {
log.error(_me + ': can\'t add a panel without a data object that has .contents');
return;
}
// Add the panel to the dom and track it in memory
$panel = $(tmpl(panelTemplate, panelData));
$panel.css('width', _panelWidth);
_configureRandomPanel($panel.find('.panel'));
_panels.push($panel);
_$panelBox.append($panel);
// Record the panel position in memory
panelPos = _calculatePanelPos(_panels.length - 1);
_panelPositions.push(panelPos);
}
};
@SimplGy
Copy link
Author

SimplGy commented Apr 3, 2012

I am looking for opinions on whether it's acceptable to do an error check in an if and return out of it. I recall the traditional CS wisdom is to only return at the bottom of the method, but it seems cleaner to exit on error in line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment