scripting maintainability

134
Scripting Maintainability Christian Heilmann Fronteers Conference 2008, Amsterdam, Holland

Upload: christian-heilmann

Post on 19-Aug-2014

23.794 views

Category:

Education


1 download

Tags:

DESCRIPTION

My presentation for the Fronteers conference in September 2008 in Amsterdam.

TRANSCRIPT

Page 1: Scripting Maintainability

Scripting

Maintainability

Christian Heilmann

Fronteers Conference 2008, Amsterdam, Holland

Page 2: Scripting Maintainability

Hello there, I’m Chris.

Page 3: Scripting Maintainability

I’m here to talk about maintainability of code.

Page 4: Scripting Maintainability

Which really is not that easy.

Page 5: Scripting Maintainability

I was also asked to deep-dive into the subject.

Page 6: Scripting Maintainability

Oh well, let’s do this.

Page 7: Scripting Maintainability

Humans and computers don’t work well together.

Page 8: Scripting Maintainability

Computers love things structured and logical.

Page 9: Scripting Maintainability

Humans, on the other hand like to tweak, fiddle and find

their own way.

Page 10: Scripting Maintainability

Photo of a desire

path – a shortcut people

take to avoid having to go around a corner.

http://www.flickr.com/photos/skuds/602082016/

Page 11: Scripting Maintainability

Humans also love to

bend the rules.

Page 12: Scripting Maintainability

Photo of a parking lot with a barrier and

tire marks around the barrier on each side.

Page 13: Scripting Maintainability

All of this makes it damn hard to create maintainable

products.

Page 14: Scripting Maintainability

Especially in our market, as we are dealing with geeks.

Page 15: Scripting Maintainability

Photo of a geek.

Page 16: Scripting Maintainability

Finding easily maintainable code is very rare.

Page 17: Scripting Maintainability

The reasons are several tales of woe:

Page 18: Scripting Maintainability

The Village Bicycle Syndrome

The Pot Noodle Syndrome

The Lego Box

The Tale of the Missing Spanish Gentleman

The Truffle Shuffle

Page 19: Scripting Maintainability

The village bicycle is where everyone can have a ride.

Page 20: Scripting Maintainability

Sadly, this is what JavaScript has become, too.

Page 21: Scripting Maintainability

Backend Engineer

Designer

SystemServerAdmin

JavaScript

Page 22: Scripting Maintainability

Each of these will approach JavaScript in a different

manner and leave their own brand of confusion behind.

Page 23: Scripting Maintainability

Unlike the village bicycle they are not likely to help

keeping it in a working condition.

Page 24: Scripting Maintainability

Mainly because each of these comes in with a different idea

of what JavaScript is for.

Page 25: Scripting Maintainability

We have to find a way to work around this – more on

that later.

Page 26: Scripting Maintainability

However, a lot of hit & run editing is the cause for the

second syndrome.

Page 27: Scripting Maintainability

The pot noodle syndrome is that your code turns into an

instant meal.

Page 28: Scripting Maintainability

Cheap, hot, quick, immediately satisfying and

something you can prepare in any state of mind and

intoxication.

Page 29: Scripting Maintainability

The problem of pot noodle code is that it is far too easy

to sell and get accustomed to.

Page 30: Scripting Maintainability

Shortcuts don’t take much time and give you instant

success.

Page 31: Scripting Maintainability

One of the signs of pot noodle code is that it fixes short term

issues with not much effort.

Page 32: Scripting Maintainability

It is the kind of code that someone with delusions of knowledge adds quickly, shows to a manager and

proves thus that you “experts” overcomplicate

everything.

Page 33: Scripting Maintainability

Examples:

Inline style blocks, innerHTML solutions to create complex

HTML, trusting user data, Ajax requests without timeout or

failure cases.

Page 34: Scripting Maintainability

user = forms.main.name.value;if(user == ‘’){div = document.createElement(‘div’);div.style.border = ‘1px solid red’;// div.style.fontface = ‘Arial’div.innerHTML = ‘<font face=arial color=red>Enter a user Name!’;error = document.getElementById(‘error’);error.appendChild(div);

}

Page 35: Scripting Maintainability

Which leads to the other tale: The Lego box.

Page 36: Scripting Maintainability

As a kid, I had this massive box with all my Lego bricks.

Page 37: Scripting Maintainability

Being the youngest, I inherited a vast and totally unordered arrangement of

bricks.

Page 38: Scripting Maintainability

Which meant that whenever I built something, about 80% of

my time was spent rummaging noisily through

the box...

Page 39: Scripting Maintainability

...scattering bricks all over the room and still not finding

what I was looking for.

Page 40: Scripting Maintainability

...which of course drove my mom up the wall at 6 a.m.

Page 41: Scripting Maintainability

...so she got me lots of little boxes and we spent a few

days organizing all the bricks into those.

Page 42: Scripting Maintainability

The things I build afterwards were much prettier, more

complex and I was building them a lot faster.

Page 43: Scripting Maintainability

I didn’t break any bricks rummaging or stepping on

them and the noise level was much lower.

Page 44: Scripting Maintainability

The same can work for code.

Page 45: Scripting Maintainability

By separating the different tasks into the right boxes, we

stop the pot noodle syndrome.

Page 46: Scripting Maintainability

Everything visual is achieved with CSS!

Page 47: Scripting Maintainability

HTML that makes sense without JavaScript should not

be created with JavaScript.

Page 48: Scripting Maintainability

HTML that *only* makes sense *with* JavaScript should be created with

JavaScript.

Page 49: Scripting Maintainability

Anything that is likely to change should not be

scattered all over your code but in a central location.

Page 50: Scripting Maintainability

Let’s take a look at an example.

Page 51: Scripting Maintainability

Screenshot of

the Yahoo Music API

video player.

http://ydntest.com/musicapi/playerfull.html

Page 52: Scripting Maintainability

Everybody Duck!

Page 53: Scripting Maintainability

There will be code

Page 54: Scripting Maintainability

function videosreceived(data){ // create a new video player container var player = document.createElement('div'); player.id = 'videocontainer'; document.body.appendChild(player); // inject the video player with the id 'videoplayer' var so = new SWFObject('http://d.yimg.com/cosmos.bcst.'+ 'yahoo.com/up/fop/embedflv/swf/fop.swf','videoplayer','512', '322', '9', '#ffffff'); so.addVariable('eID','1301797'); so.addVariable('ympsc','4195351'); so.addVariable('lang','en'); so.addVariable('shareEnable','1'); so.addParam("allowFullScreen","true"); so.addVariable('enableFullScreen','1'); so.addVariable('autoStart','0'); so.addVariable('eh','bandsPlayer.handler'); so.addParam('allowScriptAccess','always'); so.write('videocontainer');

// get a reference to the video player - this needs to be global! vidplayer = document.getElementById('videoplayer');

Page 55: Scripting Maintainability

var videos = data.Videos.Video; var list = document.createElement('ul'); for(var i=0,j=videos.length;i<j;i++){ var title = videos[i].title; var id = videos[i].id; var photo = videos[i].Image.url; // resize photo photo = photo.replace('=385','=75'); // turn duration into minutes and seconds var duration = videos[i].duration; var mins = parseInt(duration/60); var seconds = duration % 60; if(seconds < 10){ seconds = '0' + seconds; } duration = mins + ':' + seconds; var id = videos[i].id; var li = document.createElement('li'); // creata a link pointing to the playID method of the movie var a = document.createElement('a'); a.setAttribute('href','javascript:vidplayer.playID("v"+'+id+')'); var img = document.createElement('img'); img.setAttribute('src',photo);

Page 56: Scripting Maintainability

img.setAttribute('alt','Video screenshot of: ' + title); a.appendChild(img); a.appendChild(document.createTextNode(title+' ('+duration+')')); li.appendChild(a); list.appendChild(li); } document.body.appendChild(list); }

Page 57: Scripting Maintainability

Let’s clean this up!

Page 58: Scripting Maintainability

yahoomusicplayer = function(){ var configuration = {}; var vidplayer = 0; function init(){}; function buildplayer(id){}; function received(data){}; function sanitize(data){}; function getMinutesAndSeconds(duration){}; function createItem(videodata){}; function play(id){}; return{ init:init, received:received, play:play, config:configuration }; }(); yahoomusicplayer.init();

Page 59: Scripting Maintainability

Configuration objects rule!

Page 60: Scripting Maintainability

If you make them accessible, you can also allow for programmatic access.

http://www.wait-till-i.com/2008/05/23/script-configuration/

Page 61: Scripting Maintainability

*.className is your friend!

Page 62: Scripting Maintainability

How can you hide a lot of different elements with a

certain class in a document?

Page 63: Scripting Maintainability

// it's 2008, baby, yeah!if(document.getElementsByClassName){ var sections = document.getElementsByClassName('hide'); for(var i=0,j=sections.length;i<j;i++){ sections[i].style.display = 'none'; }// we're still in Redmond} else { var sections = document.getElementsByTagName('div'); var check = new RegExp("(^|\\s)hide(\\s|$)"); for(var i=0,j=sections.length;i<j;i++){ if(sections[i].className.match(check)){ sections[i].style.display = 'none'; } }}

Page 64: Scripting Maintainability

alternatively...

Page 65: Scripting Maintainability

_x$_2_(‘hide’).libraryMagicPixies.each(this.hide(‘snappy’));

Page 66: Scripting Maintainability

How about?

Page 67: Scripting Maintainability

var b = document.body;var c = b.className ? b.className + ' js' : 'js';b.className = c;

Page 68: Scripting Maintainability

body.js div.hide{ position:absolute; left:-4000px;}

Page 69: Scripting Maintainability

You use the right tool for the job, keep the headache of

designing to those who care about it and avoid looping to

boot!

Page 70: Scripting Maintainability

You also give the CSS designer a handle to style a

non-JavaScript and JavaScript version.

Page 72: Scripting Maintainability

The Tale of the missing Spanish Gentleman

Page 73: Scripting Maintainability

Every product comes with a free Spanish novel.

Page 74: Scripting Maintainability

About a man called Manual.

Page 75: Scripting Maintainability

Spoof of an IKEA

manual explaining

JavaScript

Page 76: Scripting Maintainability

Documentation is a lot harder than we think.

Page 77: Scripting Maintainability

The reason is the diversity of people that will use your

script.

Page 78: Scripting Maintainability

Biggest BS statement ever:

Good code explains itself.

Page 79: Scripting Maintainability

“Yes that is understandable to you, as you are Dean Edwards, but I am not”

SCNR :)

Page 80: Scripting Maintainability

The biggest issue with documentation?

Page 81: Scripting Maintainability

How do you make sure it doesn’t get outdated?

Page 82: Scripting Maintainability

We are very likely to update and fix code, but not the docs.

Page 83: Scripting Maintainability

Therefore a great concept is to have at least part of the documentation generated

from comments in the code.

Page 84: Scripting Maintainability

Big libraries do this to provide an in-depth

documentation of what is what.

Page 85: Scripting Maintainability
Page 86: Scripting Maintainability

... which is a cool start, and somewhat of a safety net.

Page 87: Scripting Maintainability

... but it also poses a very high barrier of entry.

Page 88: Scripting Maintainability

For the more visual and hands-on learners you also

need to provide step-by-step tutorials and shortcuts.

Page 89: Scripting Maintainability

One structure for tutorials has become a very successful

blue-print:

Page 90: Scripting Maintainability

What does it do?

Working Example

Full code

Chunks of code interspersed with explanations

Page 91: Scripting Maintainability

You can generate this from comments in the source code

of a code example using a backend script:

http://is.gd/25A8http://icant.co.uk/sandbox/videoplayer

Page 92: Scripting Maintainability

/*startmeta name: Yahoo Music API video player title: Detailed explanation of the demo script for the Yahoo Music API video player date: 12/09/2008 description: This is a step by step explanation of the cleaned up demo example for the Yahoo Music API video player tags: yahoo,music,api,videos version:1.0 authors:Christian Heilmann (http://wait-till-i.com) license:BSD license (http://wait-till-i.com/license.txt)endmeta*/

Page 93: Scripting Maintainability

/*We're using the "revealing module pattern":http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/ to define the main script. In this case, the main module name will be #yahoomusicplayer#.*/yahoomusicplayer = function(){/*The configuration object defines the things that are likely to change, in this case the IDs of the player container and the video player itself. The label is the alternative text of the videothumbnails, it will be followed by the title of the video.*/

Page 94: Scripting Maintainability

var configuration = { CSS:{ IDs:{ playerContainer:'videocontainer', player:'videoplayer' } }, labels:{ imagealt:'Video screenshot of: ' } };[...]

Page 95: Scripting Maintainability
Page 96: Scripting Maintainability
Page 97: Scripting Maintainability
Page 98: Scripting Maintainability
Page 99: Scripting Maintainability
Page 100: Scripting Maintainability
Page 101: Scripting Maintainability

Copy and Paste examples are amazingly successful.

Page 102: Scripting Maintainability

Make very sure that they work, and that they are high

quality examples.

Page 103: Scripting Maintainability

A lot of people will not bother learning how things work...

Page 104: Scripting Maintainability

...but fiddle around with the examples until they do what

they are asked to create.

Page 105: Scripting Maintainability

Documentation is never a waste of time...

Page 106: Scripting Maintainability

... unless people don’t find it.

Page 107: Scripting Maintainability

Make sure that new developers get on the project

from the documentation to the code – not the other way

around.

Page 108: Scripting Maintainability

This avoids the last issue of the list.

Page 109: Scripting Maintainability

The Truffle Shuffle

Page 110: Scripting Maintainability

The Truffle Shuffle

Page 111: Scripting Maintainability

It is when something that should be small is far too big

for its own good.

Page 112: Scripting Maintainability

a.k.a.

Code Bloat

Page 113: Scripting Maintainability

Code bloat happens when code that is not explained or structured gets in the wrong

hands.

Page 114: Scripting Maintainability

Very often this is the case with CSS.

Page 115: Scripting Maintainability

Instead of editing the existing CSS selectors and values,

maintainers just add another line...

Page 116: Scripting Maintainability

...increasing the specificity by adding another selector until you end up with things like:

Page 117: Scripting Maintainability

body div#main ul#main li a.active span{color:#000;

}

Page 118: Scripting Maintainability

A JavaScript classic is also just to add other functions and

call them immediately at the end of the script or with another window.onload.

Page 119: Scripting Maintainability

I’ve talked in length about this a year ago:

http://icanhaz.com/codebloatinfo

Page 120: Scripting Maintainability

However, here are some tricks to avoid code bloat.

Page 121: Scripting Maintainability

Separate out – each method does one and only one task.

If you are likely to need to do the same task over and over, create a tool method (f.e. creating a link, adding new script node to the head)

Collate related task methods into modules.

Page 122: Scripting Maintainability

Document the modules:

myapp.Dom does all the the Dom manipulation.

myapp.validate does all cleaning of user data.

Explain how to extend the modules!

Page 123: Scripting Maintainability

The most important:

Page 124: Scripting Maintainability

Have a build process!

Page 125: Scripting Maintainability

Live code is for machines – development code is for

humans!

Page 126: Scripting Maintainability

Minify, strip comments, collate into a single include

file and tag as

GENERATED, DO NOT EDIT!http://www.ejeliot.com/blog/72

Page 127: Scripting Maintainability

What about code standards?

Page 128: Scripting Maintainability

Here’s an idea: instead of forcing developers to change their ways, let’s think about

using technology.

Page 129: Scripting Maintainability

The place where code needs to be in an agreed standard is

inside the code repository.

Page 130: Scripting Maintainability

The easiest way to make this work is by automatically

converting it to this format when the code is submitted.

Page 131: Scripting Maintainability

So instead of arguing pro and cons of writing code in a

certain format, let’s script our editors to do that for us!

Page 132: Scripting Maintainability

The safest way is straight and narrow – no confusion, no

surprise.

Page 133: Scripting Maintainability

More reading:http://delicious.com/codepo8/forfronteers08

Page 134: Scripting Maintainability

Thanks!Chris Heilmann

http://scriptingenabled.org

http://wait-till-i.com