var isProxyBased = (/S40[\w]{3,5}Browser|Opera\sMini\//i).test(navigator.userAgent);
if (('querySelector' in document && 'localStorage' in window && 'addEventListener' in window && !isProxyBased) || (isIE > 6 && document.getElementById('js-holepunched'))) {
// do stuff
}
var cutsTheMustard = 'querySelector' in document && 'localStorage' in window && 'addEventListener' in window,
isNotProxyBased = !/S40[\w]{3,5}Browser|Opera\sMini\//i.test(navigator.userAgent),
modernDevice = cutsTheMustard && isNotProxyBased,
holepunched = isIE > 6 && document.getElementById('js-holepunched');
if (modernDevice || holepunched) {
// do stuff
}
I refactored this code by making just a couple of very basic tweaks…
isProxyBrowser
isProxyBased
logic so it becomes isNotProxyBased
(this meant we didn’t clutter modernDevice
with extra syntax and made it as readable as possible)Is there any thing more we could do with this code to make it as simple as possible to understand?
Well, one small tweak we could make would be to simplify the conditional even further. We could do this by creating another variable (again with a helpfully descriptive identifier) to hold the check of modernDevice || holepunched
, like so…
var cutsTheMustard = 'querySelector' in document && 'localStorage' in window && 'addEventListener' in window,
isNotProxyBased = !/S40[\w]{3,5}Browser|Opera\sMini\//i.test(navigator.userAgent),
modernDevice = cutsTheMustard && isNotProxyBased,
holepunched = isIE > 6 && document.getElementById('js-holepunched'),
enhancedExperience = modernDevice || holepunched;
if (enhancedExperience) {
// do stuff
}
One thing to be aware of is: refactoring can actually be a bad thing if you don’t know why you’re doing it. If you’re just blindly following predefined rules of refactoring then the above small tweak could end up making the code harder to read.
Imagine if we were in a situation where there wasn’t a logical association between modernDevice
and holepunched
. We could end up creating a variable like passesOurChecks
(this is a poor example I know). Which would mean this new variable would actually make the code slightly harder to read because it wouldn’t be descriptive enough and would likely mean the reader would need to check what the value of that variable was to better understand the code.
Just something to keep in mind.