Skip to content

Instantly share code, notes, and snippets.

@rgarner
Created June 26, 2012 09:02
Show Gist options
  • Save rgarner/2994562 to your computer and use it in GitHub Desktop.
Save rgarner/2994562 to your computer and use it in GitHub Desktop.
Self-evident vs. Script-y code
#
# This is a little script to pop up an #ico cookie consent banner with a clickable #ico-ok element in it.
# I wrote the "self-evident" version first. I expanded it out to the script-y version and added comments.
#
# Questions:
#
# * Which is easier to read?
# * Which is easier to maintain?
# * Why?
#
# Self-evident version
#
COOKIE_NAME = 'ICO_auth'
ONE_YEAR = 3600000 * 24 * 365
class ICO
@setup = () -> show() if shouldShow()
shouldShow = () -> navigator.cookieEnabled and not consentGiven()
consentGiven = () -> document.cookie.indexOf(COOKIE_NAME) != -1
giveYearsConsent = () ->
expire = new Date();
expire.setTime(new Date().getTime() + ONE_YEAR);
document.cookie = COOKIE_NAME + "=1;expires=" + expire.toGMTString();
show = () ->
$('#ico-ok').click ->
giveYearsConsent()
$('#ico').hide('slow')
$('#ico').show('slow')
$(document).ready ->
ICO.setup()
#
# Script-y version with comments
#
# If we're using cookies and we don't have a record of the user clicking ok
$(document).ready ->
if navigator.cookieEnabled and (document.cookie.indexOf('ICO_auth') == -1)
# Then when the user clicks ok
$('#ico-ok').click ->
# We set a cookie to expire a year from now
expire = new Date();
expire.setTime(now.getTime() + 3600000 * 24 * 365);
document.cookie = "ICO_auth=1;expires=" + expire.toGMTString();
# And hide the popup
$('#ico').hide('slow')
$('#ico').show('slow')
@rgarner
Copy link
Author

rgarner commented Jun 26, 2012

Personally, after I'd extracted the script-y version, I found it easier. But it's easier from my point of view, or maybe other coders'. And only at that size. If I'd expanded out a much bigger example, the bigger example wouldn't scale. I suppose what I'm trying to get at is this: below a certain size and for a low likelihood of required maintenance, is the second form ever acceptable? Because mostly, I can't bring myself to write it.

There's also the dimension of the user language. The first example has giveYearsConsent and consentGiven, which (if you accept correctness as a given), are obvious extensibility points as expressed in language you'd see from a UX guy or written on a wireframe. The second version requires a little more translation as it's all implementation and no explicit intent.

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