Thursday, 21 October 2010

Optimising jQuery each

Yea, another optimisation post, it's not an obsession, it's just this is pretty interesting. Jamie Stewart tweeted about this article on optimising jQuery each. I really like the idea of creating an empty jQuery object and passing context to it - it just seems smart. I'm always wary of optimising prematurely though so I wrote a little speed test page of my own. You can run the tests yourself, and then come back and comment :).

The results of which seem to show to me that whilst the optimisation is faster, it's probably not going to be noticeably faster in my day to day usage. Still, faster is faster, right? Well, not always, I would see using this as a standard replacement for .each as a premature optimisation. Whilst it is faster, it's not no-brainer faster; there are other factors to consider:
  • The optimisation comes in plugin form, which is extra code to download and possibly an additional http request

  • Breaking from jQuery core means a possible break from future jQuery optimisations

  • Faster, IMHO in this case, doesn't trump readability
I would definitely consider this method for large iterations and when I know something is slow, but it won't become my go to replacement for .each - despite how cool an idea it is.

Monday, 4 October 2010

Web blasphemy

A while ago Andrew Donaldson wrote an interesting article on how "gut reactions" to things in web development can actually close our eyes to new ideas (in which he brutally mangles my approach to CSS :-)). I think the key point in our discussions is summed up nicely: "When discussing the presentation with my friends I remember saying 'I don’t know why I don’t like it, but I just don’t'".

This week I was watching Julien Lecomte's awesome talk on high performance ajax which touches on this subject which a worthy example. He is talking about breaking a small rule for a big payoff and mentioned replacing span class="bold" with the deprecated b element to make a big file size saving (in his example where displaying perhaps 1000 results).

I found myself immediately thinking "well, surely you'd page the results and so the saving would be dramatically lessened". Which, of course, is not relevant to the point being made, but was a knee jerk reaction on my part to the blasphemy of using deprecated elements! It made me think of how many other possible savings or great ideas I'd missed because my standards advocacy had placed me firmly back inside the box.

Friday, 1 October 2010

Look on my works, ye mighty, and despair!

I've been doing a lot of yoga recently, which I'm really enjoying. Unfortunately, being the least flexible person on the planet I manage to both suck and blow simultaneously at yoga. I'm also running twice a week, which is a trial... Since I hurt my back, my gait has shortened and it takes forever to run anywhere.

So it was nice to be in the gym today and actually do something well. 5 sets of 5 reps on the bench with 120kg supersetted with weighted pullups:
  • 7 reps warm up
  • 8 reps with 5kg additional weight
  • 6 reps with 10kg additional weight
  • 5 reps with 15kg
  • 5 reps with 15kg
  • 4 reps with 20kg
Then some triceps to finish off. It was a good day :)

Friday, 30 July 2010

CSS Restructure - specificity

By creating very non specific classes and giving standard styling to elements, it was relatively simple to move specificity from the declarations to the stylesheet layout. Now, I realise that many people don't work in an environment where, to some extent, they can ride roughshod over the designs. The changes I made to the designs had (to my eye) a negligible effect on the overall look, but I would be interested to see what happens in a company where designs are signed off and set in stone.

I separated the style sheet into 3 sections, the first being the most basic styles, the ones destined to be over written. The rounded corner classes are an example, because the border colour would be over written. I decided not to put any padding or margins in these declarations, just incase I wanted to use them vanilla, over writing padding to reset it to zero seemed like a poor move.

The second section of the css was for extensions such as colour schemes and list styling. I also put those sections of the site which require specific styling in here. Stubbornella warns against styling id's, which I think is excellent general advice and aligns with the general zeitgeist of non specific declarations. However, I did use id's in areas that I knew were one of a kind styling issues as it removes the possibility of unwanted clashing of styles and is faster at render time.

The final section was kept for very simple helper classes that were meant to over write all other styles. These classes were generally single declarations used as extensions. For example, I had a styled list which created a toolbar of image icons. These were usually floated to the top right of their parent element, but in a particular case it was more appropriate to have them floated to the left. The single declaration float left class was added to the list and voila.

CSS Restructure - helper classes

The main thrust here is to develop a series of classes which do very common things and make them non-specific enough to be extended by another class. I looked through the designs and got an idea for what things were common and how they differed from section to section.

A pretty good example was that we had a few lists with background images, a header, some content text and a link. The header and link colours might change depending on what the list was, as might the size of the background images.

At this point, you need to make a judgement call on the level of granularity you need. Is there a need for separate colour styles and sizing? Obviously the more granular you go, the more class names you have to add to an element, which never feels bomb proof to me. In this case, I felt 2 classes would suffice.

I created a base background image list class, which set the most common properties I would need, such as no-repeat on the background, some padding and a margin. This class was given to all of the lists and then extended with another class that gave the list specific left padding, minimum height and heading colour.

Once those basics were done, I found I actually had quite a good tool set to create future interface objects without further css. Instead of the standard square border, 1 on top of the other list I already had, I could create a list of discrete lozenges by adding rounded corner and margin classes. These new interface objects all look correct, because the reflect the basic design elements of the page. Thus developers can create perfectly acceptable demo's and mock-ups without front-end intervention.

CSS Restructure - uniformity

Normally when I work on a project, I tend to take the designer's work as a guideline and standardise things so that I don't have to over complicate my css. If the page headings vary between 32 - 34px I will standardise on 1 size. The same with shades of colour, padding and margin. However, on this project, the designs were so nice, that I want to render them perfectly. I was also enamoured with the fact that I was working on a product, so I would actually have the time to change things later if they got out of control.

Taking rounded corners as an example (I am using css only rounded corners) I noticed that the declarations can be a bit bulky and that we used a wide number of radii, ranging from 2-7. I decided to simplify (which many dev's simply won't have the ability to do) this down to 2 (a 3px radius and a 6). I toyed with the idea of styling a box for each of these, with rounded corners, padding and a background colour, then using extendion classes to change those values (which I still think is a valid approach, but I was worried about needing a class to reset). I decided to go for granularity and created 2 classes: rc6 and rc3 which contained only the border styles.

I proceeded through margins, padding, font sizing in this manner. My process being that I would take the top 2 - 3 most commonly used declarations in each case. Anything deemed too far removed from any of these declarations would be placed in a more specific class.

I then created some colour schemes and styling classes to give a more specific look and feel. These I named generically, so the styles could be altered without making a mockery of the class name :). Again, slight differences in the shading of colours were lost.

The end result of this process is a site which, to date, no one has noticed the loss of fidelity. Things line up effortlessly and future elements can be pretty much guarenteed to line up. I have a 3 column layout, each column may start with either an image, a header or plain text. Regardless of the combination, even with user defined markup, all the elements line up. I am really pleased with the way this has worked out and inted to meddle heavily in all future designs :)


CSS Restructure

I recently watched "The top 5 mistakes of massive css" and got to thinking about how to structure css. For a while I've been separating structure and chrome and enjoying small helper classes. I'd been drawn away from delving too deeply into helper classes by the idea that single declaration specificity was a way to optimise page drawing time (i.e. div.className over .className).

The idea I took from the video above was that my page drawing savings would be lost against the page weight savings. Another big draw for me was the idea of maintainability. I am really enjoying working on a product at present, one of the main advantages is that maintainability is much more relevant and worthy of additional investment. So i decided to restructure and after looking at the "oo css" code, I decided to restructure on 3 main principles.

  1. Uniformity (reducing complexity)
  2. Using small helper classes
  3. Managing specificity
Conclusion
I found the process quite challenging, but very rewarding. I was shocked when I saw the results though, a reduction in the unzipped css file sizes from 47K to 26K. That's a pretty big saving, there was cruft in the files from the constant process of change during a build cycle, but even so...

I am convinced that my current method of working is advantageous, but I have not finished experimenting or optimising yet. What I like most about this process is that you provide yourself with a series of tools to build future interface objects without adding more css.

I found myself simply combining helper classes to great effect, for example, when it came to creating the paging list, I realised that I could even design it myself. All I needed was to make a list display inline, the li's should have the primary colour as a background and have rounded corners. Well, all of those styles already existed, 2 classes on the ul and one on the li.

One concern I had initially was that multiple helper classes on each li of a long list would be a real pain. But I found that I rarely needed that, 4 was the most classes on any particular element and that was never a repeated element. However, it may just be that this particular site didn't require too much granularity of helper classes.

I also decided to obfuscate my class names somewhat for the sake of optimisation. Hence rounded corners class name became rc, list styling one became ls1 and so on. I have written documentation to define these classes, but time will tell if this is a good idea.

My theory is that the application of any methodology must be directly relevant to project. I really like this way of working and it seems to be ideal for my current project. I will continue using it until I either find a better way or until I find a project on which this methodology is non optimal. This article is simply an explanation of how I worked with the cssfor my project, not an endorsement of this as standard practice.

Wednesday, 21 July 2010

The Doors of Perception

Just finished reading Huxley's The Doors of Perception. Very interesting as a whole, but this particular passage struck me as a wonderful expression of thoughts I have been having about our limited ability to percieve reality:

Reflecting on my experience, I find myself agreeing with the eminent Cambridge philosopher, Dr. C. D. Broad, "that we should do well to consider much more seriously than we have hitherto been inclined to do the type of theory which Bergson put forward in connection with memory and sense perception. The suggestion is that the function of the brain and nervous system and sense organs is in the main eliminative and not productive. Each person is at each moment capable of remembering all that has ever happened to him and of perceiving everything that is happening everywhere in the universe. The function of the brain and nervous system is to protect us from being overwhelmed and confused by this mass of largely useless and irrelevant knowledge, by shutting out most of what we should otherwise perceive or remember at any moment, and leaving only that very small and special selection which is likely to be practically useful." According to such a theory, each one of us is potentially Mind at Large. But in so far as we are animals, our business is at all costs to survive. To make biological survival possible, Mind at Large has to be funneled through the reducing valve of the brain and nervous system. What comes out at the other end is a measly trickle of the kind of consciousness which will help us to stay alive on the surface of this Particular planet. To formulate and express the contents of this reduced awareness, man has invented and endlessly elaborated those symbol-systems and implicit philosophies which we call languages. Every individual is at once the beneficiary and the victim of the linguistic tradition into which he has been born - the beneficiary inasmuch as language gives access to the accumulated records of other people's experience, the victim in so far as it confirms him in the belief that reduced awareness is the only awareness and as it bedevils his sense of reality, so that he is all too apt to take his concepts for data, his words for actual things. That which, in the language of religion, is called "this world" is the universe of reduced awareness, expressed, and, as it were, petrified by language. The various "other worlds," with which human beings erratically make contact are so many elements in the totality of the awareness belonging to Mind at Large. Most people, most of the time, know only what comes through the reducing valve and is consecrated as genuinely real by the local language. Certain persons, however, seem to be born with a kind of by-pass that circumvents the reducing valve. In others temporary by-passes may be acquired either spontaneously, or as the result of deliberate "spiritual exercises," or through hypnosis, or by means of drugs. Through these permanent or temporary by-passes there flows, not indeed the perception "of everything that is happening everywhere in the universe" (for the by-pass does not abolish the reducing valve, which still excludes the total content of Mind at Large), but something more than, and above ah something different from, the carefully selected utilitarian material which our narrowed, individual minds regard as a complete, or at least sufficient, picture of reality.

Tuesday, 6 July 2010

Three virtues of a programmer

This is one of my favourite Larry Wall quotes, about what makes a good programmer:
  1. Laziness - The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful, and document what you wrote so you don't have to answer so many questions about it. Hence, the first great virtue of a programmer. Also hence, this book. See also impatience and hubris.

  2. Impatience - The anger you feel when the computer is being lazy. This makes you write programs that don't just react to your needs, but actually anticipate them. Or at least pretend to. Hence, the second great virtue of a programmer. See also laziness and hubris.

  3. Hubris - Excessive pride, the sort of thing Zeus zaps you for. Also the quality that makes you write (and maintain) programs that other people won't want to say bad things about. Hence, the third great virtue of a programmer. See also laziness and impatience.

Training

Quite pleased today. I hurt my foot doing sprints last weekend, so I've been doing machine based cardio this week. Rowed a 10k today in 39:53, which isn't particularly fast, but it's the first time I've rowed in a few years and it felt pretty good.
I've let my squats go though, due to all of the running I've been doing. I want to get back to that, but it always seems to take so long to recover...

Tuesday, 15 June 2010

I'm comic-sans asshole

Timothy McSweeney wrote the an awesome "short imagined monologue" about the font Comic Sans today. It's been an immediate web hit, because it's an outstanding piece of work. For some reason it occured to me that at a certain section, the tone of the writing was somewhat incongruent with the visual style of comic sans... I've reproduced it here in the spirit of fun, note the use of web safe colours - papayawhip always made me smile.

While Gotham is at the science fair, I'm banging the prom queen behind the woodshop. While Avenir is practicing the clarinet, I'm shredding Reign In Blood on my double-necked Stratocaster. While Univers is refilling his allergy prescriptions, I'm racing my tricked-out, nitrous-laden Honda Civic against Tokyo gangsters who'll kill me if I don't cross the finish line first.

Saturday, 12 June 2010

Alex Jones

Have been listening to Alex Jones a fair bit recently. He is a proper old fashioned fire and brimstone preacher, but for conspiracy theories. He was ranting about how the "global powers" want to cull the human race, which is clearly an act of almost unthinkable evil. It made me recall a poster at work. It was complaining about how 1,000,000 people die in Africa every year of Malaria and asking me to donate a small amount of money to stop this happening. I recall pointing out to a colleague that it would be irresponsible of me to cure Malaria without paying for those additional people to eat.

As I was walking home from the gym (through Glasgow town to the less salubrious quarter of Partick) I pondered this and thought that at some point, there is likely going to be a time where there are too many people for the Earth's limited resources to support (at our current level of consumption). Ok, so, I still can't imagine culling 70% of the Earth's population to save my own bacon. But, lets look at it from another perspective - imagine the earth is failing, perhaps it's falling into the sun or something. A rocket ship has landed and can take 30% of the people on earth to safety. Would you want to be on the ship? Would it be ok to leave 70% of the population behind?

Thought experiment

As I was pondering all of this, I came out of my reverie as I was accosted by a very drunk young man (at 11am on a Saturday - gooooooo Glasgow) looking for his bus fare home. I looked at the horror show of life shuffling by me: old men in suits sat in doorways too drunk to stand; fat mums screaming at their kids, cigarette in hand and I wondered if it would be such a terrible thing if these people didn't make it onto the rocket ship?

As a thought experiment, I tried to snapshot a group of people in my mind and figure out the 70% who would be left and the 30 who would come with me to start a new life on another planted. During the 20 minute remainder of the walk, I found 1 other person I would want to share a planet with and I think that was only because she wasn't wearing a bra...

More Training

Shoulder

So, my trips to the physio have resulted in her relenting on the "no training" issue. Apparently, the muscle mass in my shoulder is all that's keeping it in place, so any reduction in it is allowing the joing to plummet earthwards and cause additional pain.

The physio session itself was pretty cool. I was asked to lie down on my back and push my should downwards. Apparently, my body has no concept of how to go about this. Once I got the hang of it, I could actually reduce the pain when doing things simply by holding my shoulder in the right position - win!!

Tuesday

I was shattered, so I just cycled for 30mins while watching Breaking Bad - which is awesome

Wednesday

I was shattered, so I just cycled for 50mins and did some stretching. I also used the dyna-band to give resistance to my "holding the shoulder in it's correct position" excercises, which I think is working.

Thursday

Shoulders
10 sets of 22kg dumbell press for 10 reps each. Sundry rotator cuff excercises.

Friday

10k run along the back roads near the house - felt slow, legs were bust after it.

Saturday

A somewhat lackluster chest workout. Tried benching, was fine up to 100kg, then my shoulder played up a bit. But it was my wrist that was sore - from when I fell over in the Morrisons carpark - sober

Thursday, 10 June 2010

Cormac McCarthy

After reading "The Road" Cormac pretty much went straight into my top 5 favourite authors. As well as being an awesome story, the prose are outstanding - not that I am claiming to be a literary critic, but I know the difference between a writing style that adds to the story and, say, Dan Brown: "Five months ago, the kaleidoscope of power had been shaken, and Aringarosa was still reeling from the blow".

I wanted to quote some of McCarthy's work for quick reference:

So what is the way of raising a child?

At a young age, said the judge, they should be put in a pit with wild dogs. They should be set to puzzle out from their proper clues the one of three doors that does not harbor wild lions. They should be made to run naked in the desert until...

Hold now, said Tobin. The question was put in all earnestness.

And the answer, said the judge. If God had meant to intervene in the degeneracy of mankind would he not have done so by now? Wolves cull themselves, man. What other creature could?
He also has quite an awesome turn of phrase - I am currently overusing "besotted bedlamites" to describe the denizens of Glasgow.

By dark the streets were filled with besotted bedlamites lurching and cursing and ringing the curchbells with pistol balls in a godless charivari, until the priest emerged bearing before him the crucified Christ and exhorting them with fragments of Latin...

Right, I am off to read some more...

Sunday, 6 June 2010

Red Dead Redemption

The single player aspect of this game is breath-taking, the open world is genuinely fun to explore, the scenery is spectacular (in the true sense of the word), and the quests are varied and interesting. The game also has some truly special moments, I happened upon a wounded law man, whose charges were escaping. He asked me to "get after them". I'd just been given a lasso, so I thought I would try it out; I managed to lasso the convict, tie him up, put him on my horse and return him to the lawman. The lawman thanked me and paid a finders fee, he then pulled out his pistol and shot the convict dead!

The multiplayer aspect of the game feels epic when you first enter the "free roam" section. It is almost like entering a western MMO, where you envision teaming up with your friends for gang shoot-outs against other players. Unfortunately, the game doesn't really work like that. "Free roam" is simply a foyer, where you can do a few quests while you wait for one of the standard capture the flag or death match style games to begin. These work for other games, but the single player mode sets the expectation of open play and going from that to a small arena with 5-6 other players is a let down.

Definitely worth the purchase for the single player mode.

Training Back

Back is pretty much all I can train at the moment due to a shoulder injury.
Today:
  1. 1 set 10 reps pullups
  2. 3 sets 5 reps 10kg pullups
  3. 2 sets 5 reps 15kg pullups
  4. 5 sets 8 reps 50kg dumbell row
  5. 4 sets 6-8 reps 90kg close grip pulldowns
Felt pretty strong, I was wary of the shoulder doing the pullups, but it seemed to go ok and it's no sorer after the training. Pretty tired overall though, after much more aerobic work - training for triathlons atm.