Looking for Feedback: Good coding over fast coding?

I’ve been mulling this over in my head, and here is why.

I recently changed jobs to a early beta startup and have been enjoying the ride of creating a company from scratch. I am a part of building the company not only from my shares of stock, but in my feedback on building features, or even what the company should focus on next! I consider this a bootcamp (of sorts) in the new world of entrepreneurial-ship and I love it! We run lean and fast and no code is sacred. If we ship a feature and find that it’s not doing as we expected, or worse than we expected, there is nothing to stop us from pulling the feature (and deleting the code) 2 weeks after it went live.

That said, there are still only two developers (one backend dev, and me) working on actual code and both of us are parents, so we try and keep our work / life balance pretty normal. That said, building a company requires fast work. We want to quickly prove we have “product to market fit”, and show that our service has high scalability at a low cost. I’m confident we can do it.. however when i look at our roadmap (what we want to do for 2012) and I look at our current velocity (what 2 devs can accomplish), I start to ponder the idea that my need to create loosely coupled, reusable, and clean code… is, well.. a setback.

Yeah, I do know some of the setbacks of bad coding.. foremost, it’s code you will have to live with and possibly support, for a very long time. Still, I must as the question. It’s obvious that in the short term, hardcoding and throwing many good practices will be faster in the short term. Have you seen any reason that coding faster is better than good code. (and yes, I am assuming good code takes more time, because it sure does for me).

Let me know your thoughts.

Reply to “Best Clearfix Ever” post.

I just had to reply to the clearfix post found on Marc Watts website.  I felt that some aspects of his clearfix solution needed to be cleaned up, as well as explaining a bit more about past solutions.

In the past

In the past, we used  

<div class="clearfix"></div>

and added

.clearfix { clear: both; }

to our css.  We would add the clearfix div wherever we found that our containing elements weren’t accepting a height, even if it contained content..  (For more technical nerdery on that, read more on Position Is Everything)

Soon after, we had a new fix, but it didn’t get known around the net as quickly as the div.clearfix did.  The new fix didn’t require extra markup in our css.  It used the css pseudo element.  IE6 and IE7 both don’t understand the :after pseudo element, but zoom: 1; triggers “has-layout” on them.  zoom:1; has the same effect for IE6 and IE7.  This new clearfix can be applied to a classname or applied directly to elements.  I suggest adding the classname to avoid bloating your css.


        .cf { zoom: 1; }
        .cf:after { clear: both; content: "."; display: block; height: 0; visibility: hidden; }

Dont worry that zoom isn’t set specifically for IE, unless you use zoom on your site.  Alas, if you have to, use the star hack.  

.cf { *zoom: 1; }

which will trigger IE6 and IE7.

This seems like a great thing!  Lets attach it to all elements so we never have to worry about it.

Whoa!  Hold on there.

Do we really want set all these css rules to every element in our page and require it to do all that work?  Are we really benefitting that much from it?

I say no.   Use it only when needed..  why add all that extra work to the browser?  Just because it’s good, doesn’t mean to use it everywhere..    that’s like taking a chainsaw to a steak just because you saw how well it cut the wood outside.  Use a chef’s knife, it’s more precise and things wont get messy.

Now I got one more gripe about the code Marc made.  Marc has 8 elements in his css that declare the exact same thing.  A better method is what I call a “selector array”

So instead of:


/* our Global CSS file */
    article:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
    aside:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
    div:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
    form:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
    header:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
    nav:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
    section:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
    ul:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }

/* our ie CSS file */
    article { zoom:1; }
    aside { zoom:1; }
    div { zoom:1; }
    form { zoom:1; }
    header { zoom:1; }
    nav { zoom:1; }
    section { zoom:1; }
    ul { zoom:1; }

Try “selector arrays”


    article:after,
    aside:after,
    div:after,
    form:after,
    header:after,
    nav:after,
    section:after,
    ul:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }

    article,
    aside,
    div,
    form,
    header,
    nav,
    section,
    ul { zoom:1; }

So when all is said and done, my suggestion to Marc is to only use the content hack when needed. (you will find that it isn’t needed much), and when you have a similar rules for several selectors.. bunch them up by comma-separated selectors.

Different CSS techniques and their performance

Why would I want to test performance of CSS techniques?

Here’s the background:
I am a big fan of OOCSS, (the library and the concept) but I have been using Compass, SASS lately at work. I was feeling that sometimes OOCSS and SASS seemed at odds. A friend of mine introduced me to Chris Eppstein, (the creator of Compass) and we talked about the @extend method in SASS. So I created a CSS test page, which started out as a crude way to figure out if there was a noticeable performance difference between SASS’s @extend and OOCSS’s method of CSS.

How the test works

The test makes almost 2000 boxes, all with unique backgrounds (and style rules). There are a few formats for testing (seen in the links below), and you can change to each, and test the speed differences.  Just click the links according to the style you desire.

The test uses a small script I found while researching into this test.  The script comes from Steve Souder’s blog post: Performance Impact of CSS Selectors

Steve’s post goes into a more granular approach of css selector performance, it’s worth the read.

CSS Formats

  1. OOCSS (likely fastest) double class ie.. class="box box-#" and put the base css rules on the .box class then only add the background to the unique classes
  2. Sass @extend (unsure of speed) one class ie.. class="box-3" and create a multi-selector rule with the base rules ie. .box-1, .box-2 {generics}
  3. Blatantly Bloated CSS: add all the base css to each uniqe css file. not DRY
  4. Using ID selectors Although I dont suggest this as a best practice.. it’s worthwhile for testing
  5. No CSS makes for a good baseline for testing

Code samples?

OOCSS style: one master class that holds all common rules, then an additional class for unique rules

.box {padding:25px;border:1px solid #000;border-radius:5px;}
.box-1 {background-color:#FFEE00;}
.box-2 {background-color:#00FFee;}
...

@extend style: add all unique classes to one, comma separated list of classes that use the base.

.box-1,.box-2 {padding:25px;border:1px solid #000;border-radius:5px;}
.box-1 {background-color:#FFEE00;}
.box-2 {background-color:#00FFEE;}
...

Long (or Bloated) styling: add all the common rules into each unique class separately

.box-1 {
  padding:25px;
  border:1px solid #000;
  border-radius:5px;
  background-color:FFEE00;}
.box-2 {
  padding:25px;
  border:1px solid #000;
  border-radius:5px;
  background-color:00FFEE;}
...

No CSS: kinda self explanatory

Testing Results

The testing results were quite interesting..   Lets check out some charts shall we?

So lets talk about CSS performance first.  Here are some things I see:

  • Using class selectors is almost identical speed to ID selectors
  • SASS/Compass’s @extend format is only slightly behind OOCSS format
  • The bloated format is orders of magnitude slower than the other formats
  • Even in this somewhat extreme example, the difference from best to worst is 100-200 milliseconds

And some notes on the browsers’ performance: (extra credit)

  • Most the browsers behaved about the same, just some were slightly faster
  • Firefox was the slowest of the browsers tested
  • Opera was fastest with fast CSS and slowest with slow CSS

I personally have come to two conclusions after doing this test.

  1. OOCSS and @extend format are very fast
  2. CSS Bloat does hurt performance

Oh.. and here is the test page

UPDATE:

I found some discrepancies in the testing that could affect testing, so I have removed any external file references and css rules that are possible performance gotchas (like text-shadow).

Don’t use ID selectors in CSS

Lately I have been testing out performance among css styles and I found that some of my very smart friends, started asking,”why aren’t you testing using IDs for the unique sections of the page?”.

This wasn’t a hard answer:

  1. The element is not re-usable on that page.
  2. This is the begining of a downward sprial into specificity
  3. Usually, IDs refer to something very specific, and abstracting would be tough
  4. Any performance gains picked up by using id, is negated by adding any other selector to the left fo that id

Lets delve into each of these issues at more length

The element is not re-usable on that page:

IDs are programmer’s equivalent to singletons.  There can only be one instance on the page.  This means there is no way to re-use it.  It’s usually a one to one relationship, and according to my speed testing, one line of css that’s only usable once is not a good value.  There IS a cost to css bloat.

This is the beginning of a downward spiral into specificty:

There are two main ways of overriding in css.

  1. The cascade: (anything further down the css, can overwrite the previous css rules)
  2. Specificity: the idea of creating weight by using weighted selectors.

The reason I say that specificity is a downward spiral is because the only way to overwrite a weighted rule is to add more weight..  plain and simple.  Now I am not just saying this because I heard it somewhere.  I have made and paid for this mistake.


.ModuleOfficeList .property-checkbox input
{display:block;margin-bottom:8px;_border:0px !important;}

.ModuleOfficeList .property-checkbox,
  .ModuleOfficeList .new-icon,
  .ModuleOfficeList .open-icon
{display:block}
...
.uid-officelistings .property-checkbox
{display:none !important; }

Above is real code from one of my own work from 2005.  As you can see, after awhile, I had to resort to some weighty selectors and the !important rule. This is very bad. Once we get to this point.. it takes us more time to hunt down the parent IDs we are going to use in order to overrule the current specificity. This is not team-friendly and definately not maintainable. Eventually you will specify yourself into a hole, and refactoring out specificity is nothing short of a nightmare.

On the other hand:

I have heard a few reasons why using IDs as selectors is a good thing. I’ll speak on them briefly:

Using ID selectors is faster
Yes, using ID selectors is faster than using class selectors for the simple reason that there can only be one id within a page. I even prove that is true, however the performance benefit is very small, and as soon as you add any other selector, the performance benefit is lost.


#profile-module {...}
#profile-module li {...}
.profile-module li {...}

The second selector is no faster than the third. That’s because CSS is read from right to left. so the
li
gets scanned first, which negates the speed of having an ID. Steve Souders explains how selector speed works.

IDs are meant for singletons
There are times when someone intentionally wants something to be used only once on a page. ID selectors would be useful for that purpose since they would signify once per page. My only argument here is my personal preference of having all my code be re-usable; especially since I don’t see CSS in a “programming language” way.

UPDATE: maintaible CSS / semantic HTML
There is a quite a huge following that believe using IDs are very helpful in creating maintainable CSS as well as creating a more semantic document in HTML. I think that Matt Wilcox sums it up best in his article about naming ID and classes properly. Matt brings up some valid points as reason for using IDs.

Update: Another Article advising classnames over IDs
A year after my initial post, Oli Studholme also made this post about ID selectors as well. We came up with similar conclusions. Thanks Oli!

Honorable Mention
It’s also worth mentioning, that I am not advocating getting rid of IDs from your markup alltogether. IDs can help speed up your javascript and they can relay meaning to your document.. all good things.

But in for CSS, I suggest not using id selectors. There are others that believe using id selectors do have purpose, however I dont find the good outweighs the bad. In the end, the choice is yours to make.

Using the window.location property in Javascript

I often forget how this works, so here is the different properties of window.location.
Thanks to DevGuru for the data.

To see how these work, pop open your firebug and add them to your console box and run them.

The properties:

location.hash

The hash property is a string beginning with a hash (#), that specifies an anchor name in an HTTP URL.

location.host

The host property is a string comprising of the hostname and port strings.

location.hostname

The hostname property specifies the server name, subdomain and domain name (or IP address) of a URL.

location.href

The href property is a string specifying the entire URL, and of which all other Link properties are substrings.

location.pathname

The pathname property is a string portion of a URL specifying how a particular resource can be accessed.

location.port

The port property is a string specifying the communications port that the server uses.

location.protocol

The protocol property is the string at the beginning of a URL, up to and including the first colon (:), which specifies the method of access to the URL.

location.search

The search property is a string beginning with a question mark that specifies any query information in an HTTP URL.

Loading your javascript files asynchronously

So it’s widely understood now, that performance has a direct effect on the traffic of our site.   This puts performance at a much higher priority than before.. especially if your site traffic is what pays the bills.  Steve Souders began working on website performance, initially thinking that backend performance was the key, but he quickly found out that most of the performance could be gained on the front end, with far less work than optimizing sql queries and refactoring backend code.  Since he started publishing his work, we have seen a progression of understaning what helps our websites perform better.  Here is a list of things that we can look to accomplish quickly and see vast performance improvements.

  • minification of files
  • zipping css / js files
  • pulling all css files into one
  • pulling all js files into one
  • creating image sprites that combined many images into one big sprite
  • avoid using IE specific css expressions
  • using a cdn to serve files
  • loading js at bottom of page
  • serving files from a different domain
  • serving files asynchronously after page has loaded

Want to know more about the above performance enhancements?  Go to the Yahoo Developer article explaining them in detail.   Also keep in mind that your mileage may vary.  We found this out at my current job, since we took are most popular pages, and removed all the less important parts of the page, and added them via ajax, after the page loaded.   This made the pages load screaming fast!  However, our server peaked out very quickly because it was doing about 5 times the amount of requests.  Each ajax request, even when cached, requires resources from your server.  Needless to say, we don’t have the money to drop into several more servers, so lazy loading via ajax will have to wait. Keep things like that in mind when adding performance techniques to your site.

Okay Okay, get on with it!

So you have an idea of whats going on with website performance, and the last part of the list was about serving files asynchronously after page load.   Here is a little script that simply loads files after the page has loaded

And to load these files, you only need to call the function with the script as the argument

Really, that’s about it. Fairly simple script as you can see, yet very powerful, this was basically borrowed from Google Analytics implementation of their asynchronous loading analytics.
One thing to note: I am loading the files in the opposite order than usual. The jquery.js file should be loaded first in the dom.. but since we are using insertBefore.. the first must be last and the last must be first.

Simple jQuery show / hide script

I know, I know..  this is a really simple process for those of you who have had more than an hour with jQuery.  But this article’s intention is to show just how quickly and how easily you can utilize jQuery’s robust features that make it so easy and fun to use.

So I am going to keep the explanation short and sweet. I think the code speaks for itself for the most part.

$(document).ready(function(){... does as you would think. Waits for the document to fully load.

$('.hide').hide; finds all elements with the “hide” classname and actually hides them. I am using this as opposed to hiding the elements via css so that those with javascript turned off will see the elements that are hidden. If I used css to hide the elements, then anyone with javascript turned off but have a css capable browser, would have a dysfunctional experience. Hiding elements via javascript ensures that those without javascript will still be able to see the hidden paragraph. nuf said, I think

From there, we are finding #link1 and adding a toggle when clicking. I love this because I dont have to find out the toggle status myself. I just add the two different toggle scenarios, separated by a comma, and I am good to go.

$(this).next() is how I get to the element I want to change. In this case, it is the node / element below the link that has been clicked. I kept the traversal code generic so I could use this anywhere. The only worry I have, is to make sure that the element to show / hide is precisely below the link which it relates to. This simple technique makes the code re-usable.

Next, I am using another of jQuery’s strengths by “chaining” my code to run on click. I do this by using dot for each new behavior I am passing.

.slideDown('slow').removeClass('hide').preventDefault; does three things:

  • gives the element a slide down effect when showing
  • removes the hide class from the element
  • prevents the default behavior of the link

and that’s it!

JQuery uses very simple and familiar syntax for CSS developers and it uses techniques that make it much easier to focus on what you want the page to do as opposed to figuring out how to make it work.

Example:

Show

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

How to get rid of saddle sores in cycling

I wanted to share this because I had quite a time with saddle sores last year, and I found a cheap and easy way to remedy the problem. It’s a bit unconventional, but works like a charm.

Here is the story of last year’s saddle sore issue.
My first year into riding, I bought a beginner’s roadbike, a Bianchi Brava, which served me very well.
I bought the bike and replaced the Bianchi seat with a Serfas gel seat. The semi big one with the gel top and an inset to help alleviate pressure on the private parts..

Now let me start off by saying that most of my riding problems came from inexperience and lack of knowledge. That and inproper fitting to my bike. The road bikes of today are so well made, that it is hard to find a problem with the bike… more-so, it’s a problem with the rider.

Oh yeah… gel seat… I was getting more and more fit, so I decided to take a ride with one of my more experienced cycling friends. We rode about 60 miles that day. The saddle sores were are result of that ride and for quite a few reasons.

1. I needed to have some kind of chamois cream for that area between the private parts, that can trap humidity and use it to “wear down” your skin and allow bacteria growth.

2. I needed to wash up as soon as I was done with the ride and make sure to wash the particular area of question. (fairly common knowledge, but it’s still worth noting)

3. I needed a seat / saddle that fit my butt/legs correctly.

Funny enough, the cushy saddles that would seem to be a savior to your butt, are more commonly the cause of problems such as saddle sores. They are typically too wide for your legs to move around freely and they cause chafing on the inside of your legs.

This is what happened and I tried all kinds of creams on the market to fix the problem. It only kept getting worse. Some of those creams are expensive too! So I tried something totally unconventional and i rolled up some toilet paper like a sleeping bag, and then stuck one on each side of the inside of my legs. ( using boxers wont keep the TP there, so use tightey whiteys)
I left the TP there for several hours and got another batch. I did this for two days and the problem was gone. Very nicely done.

The cost of the TP was close to 10 cents for the problem and it’s always available.

Error: Reformat using Sigmatec's reformatter

That was something like the error I recieved on my SanDisk Digital Audio Player (DAP). What was I to do.. most of the software that was able to fix it, was for windows. So I did what any intelligent tech geek-monkey would do. I turned to searched the internet. Turns out that you need a FAT or FAT32 partition installed. Mine was formatted for Mac.

How it turned out formatted for Mac is another story: Seems that dragging and dropping files works fine on my mac, but deleting files doesn’t. For some reason, the settings.dat file on the DAP does not know that I deleted files, so it holds onto the disk space. This means that deleting a file removed it from the DAP, but didn’t clear up memory. Ugh. This is why I reformatted–so that i could reclaim the space I had lost.

Unfortunately, the DAP barfed at the idea of being formatted for a mac. Trusty Google pointed me to the right direction for windows users, which could help me fix the problem. On my mac, I started Disk Utilitiy and selected the dap disk, clicked on the “Erase” tab and Erased using MS-DOS as the format. That was it!!!
The DAP worked fine from there on.

Now to only find a way around the space saving issue….. So I tried deleting the settings.dat file. This works fine, except it removes ALL files, and settings from the DAP. failure: I tried opening terminal and going to /Volumes/SDCMX/ which is the DAP drive. I used “rm” to remove files I didn’t want and that worked great. The file was gone and the space was recovered.

Happy Days.

Who says you can't buy speed?

Okay so my first post about cycling. Here is my history of cycling:

When I was young, I rode a BMX bike like every other kid but didn’t find it all that exciting. I bought a Mountain Bike years later, when they had no font shocks. I took one 17 mile ride and near killed myself. I never got on that thing again.

Then the summer of 2005 came and my car broke down for the last time. At the time, money was no object… I didn’t have any, so my elder, pastor from church suggested a bike. My elder from church was a good friend and liked to ride. This seemed like a good idea to me, so I ended up buying a bike, much to his surprise.

It was a Bianchi Brava, an entry level road bike. I couldn’t see myself in a hybrid or a Mountain Bike.. I knew I was gonna be on the road. Once I started riding the 8 mile ride to Castro Valley Bart, I began to find out how much out of shape I was. It was scary to find out that mid-level exertion would put me down on the street seeing stars and wondering if I should call 911. I found the strength to make it the 8 mile rolling hills ride to Bart station, but not much more than that.

I found a friend to commute with all winter, so the bike went untouched all that time. I had rollers, for indoor training, but I igored them. Winter was gone and so was my ride… so I had to face up and get on the bike again. To my surprise, I signed up for an MS ride of 25 miles and I faired quite well. Feeling a renewed vigor, I vowed to do the 100 mile ride in September. (2 weeks from now) and Started a very unorganized training scheme. I started passing by the Bart Station once a week and began riding the whole 20 miles to work, which meant riding the Dublin Grade, and the Castro Valley Boulevard (CVB) Hill. For most good riders, this hill is nothing, for me, I would call it Everest because it was so tough for me.

Time went on and I learned much more about recovery, overtraining, hill climbing and heart rates. I also gained a lunchtime ride with two other co-workers. Cycling was becoming very fun, not just a commute. I started to force myself to find harder hills for me to climb. Fairmont avenue in San Leandro, was my first. The first time, it took me four stops to regain strength and composure to keep riding to the top. The second time I stopped only once. That is where I stand at this point. Only time will tell if the training has been enough.

So what about this Can’t buy speed thing.
The saying goes, that you can’t buy speed. One cannot go to their local bike store, plunk down 4-6 grand and come out with a bike that will take them to the Tour de France. Bikes are not what makes you fast. Pain, training, and good recovery are what makes you fast. Well, I don’t totally believe that anymore. (actually I do, but read on..  ) My Bianchi was a pretty good bike. 30 pounds of steel frame and triple chainrings. (yes, a granny gear because I was outta shape) Roadies will never let you down if they see you on a triple chainring bike, something about the granny gear being for wussies.

I always lusted after a nice expensive bike, but I knew that was not right. It just didn’t feel right to be salivating over a bike.  After lusting but thankfully, not buying an expensive bike, I had a friend that turned me to his brother’s wonderful alumnimum bike with upgraded components. 16 pounds and only two chainrings to avoid the heckling from roadies. After much thought, prayer and rationalizing, I bought the bike for under a grand. This bike was in no way, a need. Rather it was for fun and so I purchased it, keeping that in mind. After riding this bike, I no longer lusted after any other bike.

I found that I DID in fact buy speed. Lots of it. I jetted up the hills with just as much sweat and work, but without the granny gear, I got there much faster. The lighter bike afforded me to be able to ride the hills better. With a stiff frame, more of my efforts are translated to power going forward, instead of power getting absorbed by the bike. I get tingles just thinking about taking this new bike out. Not because it is the new, fangled thing.. hardly that, because it isn’t. This is a Fuji Robaix with upgrade components (ultegra) — not the most respected bike out there. This will not get me respect in the peleton, but hopefully my perfomance on it, will.