<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title><![CDATA[Nefarious Designs]]></title>
    <link href="https://nefariousdesigns.co.uk/atom.xml" rel="self"/>
    <link href="https://nefariousdesigns.co.uk/"/>
    <updated>2019-09-24T12:07:26+08:00</updated>
    <id>https://nefariousdesigns.co.uk/</id>
    <author>
        <name><![CDATA[Tim Huegdon]]></name>
        
    </author>
    
    <entry>
        <title type="html"><![CDATA[Building Better Teams]]></title>
        <link href="https://nefariousdesigns.co.uk/building-better-teams.html"/>
        <updated>2019-09-23T13:00:00+08:00</updated>
        <id>https://nefariousdesigns.co.uk/building-better-teams</id>
        <content type="html"><![CDATA[<p><img src="/assets/img/undraw_interview_rmcf.png" alt="" /></p>

<p>Somehow you have ended up in a technical leadership role and the first thing you need to do is build a team. Alternatively, you are looking to grow an existing one. But where the heck do you start?</p>

<p>This is a challenge I am facing in my current role as CTO of Higher, a SaaS start-up in Perth, Western Australia, where we are building a platform for digital freelancers to better manage their client relationships and projects.</p>

<p>I have also faced this issue a few times previously in my career, and it can be surprisingly nuanced based on the company, team, culture, economy, and locality in which you are situated. Having worked at large corporates and start-ups alike, I can honestly say that there are always new and interesting problems to get in your way. However, there are also repeated themes that, if handled in the right way, will lead you down a path of success. With that in mind, this article is an attempt to condense my experiences as a CTO/VP Engineering at start-ups, as a Senior Development Manager at Amazon, as an Engineering Manager at Betfair and Yahoo! UK, and overall simply as a hiring manager into something that somebody out there might find helpful.</p>

<!--more-->

<h2 id="personality-goes-a-long-way">Personality goes a long way</h2>

<p>Remember you are hiring people. People just like you, with their own aspirations and concerns. Walk a mile in their shoes and remember that every person is fighting battles you know nothing about.</p>

<p>It horrifies me how often I have to bring this up, usually because someone has abstracted the idea of a team and its members away as a “resource” or “tool”. It might not be you; it could be your manager or the business as a whole. In this case it is down to <em>you</em> to bring back the humanity to the process. There are no excuses.</p>

<p>If you treat people with <strong>respect</strong>, <strong>honesty</strong>, <strong>empathy</strong>, and <strong>transparency</strong>, you will sow the seeds of success. Do not let an over-zealous leader or business process prevent you from representing both the candidates’ and the team’s best interests above everything else. Believe me, I have made those mistakes and they are some of my deepest regrets. Be open. Be approachable. Help wherever you can, even if that help is not in the best interests of the company but <em>is</em> in the best interests of the candidate. Strong relationships and respect are built on these foundations.</p>

<p>Next we need to do some preparation…</p>

<h2 id="understand-the-needs-of-the-individual">Understand the needs of the individual</h2>

<p>Understanding the needs of the individual is important so that you can ensure you are meeting those needs, both as an employer and as a leader. My boss in a previous role—whom I’m lucky enough to now consider a mentor and friend—liked to re-purpose <a href="https://en.wikipedia.org/wiki/Maslow%27s_hierarchy_of_needs"><strong>Maslow’s Hierarchy of Needs</strong></a> for this. (He liked to re-purpose it for customer/user interactions too, but that’s a post for another time.)</p>

<p>Maslow’s Hierarchy of Needs is a psychological theory that visualises five layers of human motivation in a pyramid with base needs at the bottom. Those motivations are, ordered from most needed to least:</p>

<ol>
  <li>Physiological</li>
  <li>Safety</li>
  <li>Belonging</li>
  <li>Esteem</li>
  <li>Self-actualisation</li>
</ol>

<p>For those able to see it, here’s a visualisation:</p>

<p><img src="/assets/img/maslow.svg" alt="A visualisation of Maslow's Hierarchy of Needs as a pyramid, with basic needs at the bottom (physiological, safety), psychological needs in the middle (belonging, esteem), and self-fulfilment at the top (self-actualisation)." /></p>

<p>If we re-purpose these motivations towards a person’s job, we might better specify them as:</p>

<ol>
  <li><strong>Physiological</strong>: The need for income to survive.</li>
  <li><strong>Safety</strong>: Security of job to protect income, family, health, property.</li>
  <li><strong>Belonging</strong>: Liking the people we work with, friendship, team.</li>
  <li><strong>Esteem</strong>: Confidence, achievement, respect by others, respect of others.</li>
  <li><strong>Self-actualisation</strong>: Creativity, problem solving, freedom to make a difference.</li>
</ol>

<p>If you want to build and manage great teams, it is imperative you ensure all of these things are available to the individuals that make up those teams. Often I find the first three (physiological, safety, and belonging) are taken care of, but the last two (esteem, self-actualisation) are over-looked or poorly managed. These are the basis of your working culture, not what you wear, or the music you listen to, or your out-of-work activities, and definitely not your propensity for consumption of food or drink (yes, I’m talking about after-work drinking, which many people do not enjoy, or cannot be a part of for various reasons).</p>

<p>It is important to provide definition for team members. They should have a clear understanding of their roles, their career progression, and the differences between each stage of that progression. It is these differences that will provide them with goals for individual growth, and allow them to understand why other team members are classified they way they are. This removes ambiguity and helps folks understand the expectations upon them and others, and sets-up clear boundaries and responsibilities.</p>

<h3 id="what-is-my-role">What is my role?</h3>

<p>Understanding what you do within an organisation is the foundation of those first two layers of Maslow’s hierarchy. Any form of ambiguity here introduces uncertainty, and uncertainty leads to a lack of security and potential employee churn. To avoid that, it is important we can show all employees—both new and current—that we have spent time ensuring they step into a well understood role, and that they also have room to grow and change however they choose.</p>

<p>Job specifications are required for all the roles in your business so that the individuals <em>within</em> those roles know how they are evaluated. Their use in hiring should be their secondary value. In my experience, actually defining the difference between an entry-level developer, a staff-level developer, and a senior developer—and discussing and amending those differences based on feedback from the teams themselves—will fix misconceptions and set the business up with a better understanding of roles and responsibilities. This is particularly useful where boundaries are muddied.</p>

<p>There are a lot of public resources available to help with defining job roles and expectations. I’m a big fan of the GovUK <a href="https://www.gov.uk/government/collections/digital-data-and-technology-profession-capability-framework">Digital, Data, and Technology Professional Capability Framework</a> amongst others. I’m also a big fan of <a href="https://gbr.pepperdine.edu/2001/08/the-power-of-performance-profiling/">Performance Profiles</a> as an improved method of definition. Use these resources as a guideline to define your own roles, and work with the people already in the business to better understand what <em>they</em> think their roles and responsibilities include.</p>

<h3 id="what-are-my-opportunities">What are my opportunities?</h3>

<p>As stated previously, it is important that employees understand their room for growth within both their role and organisation. This means laying out clear career paths for progression, and allowing them to figure out what direction they want to take in their own time. This does not mean only moving down the paths they are on right now; they should also have opportunities to move sideways into different disciplines or specialisations.</p>

<p>When dealing with engineering teams, it is normal to see two career tracks; one for managers (e.g. senior -&gt; lead -&gt; senior manager) and one for individual contributors (e.g. senior -&gt; principal -&gt; architect—where there is no expectation of people management). This is fantastic when thinking in terms of moving <em>up</em> the ladder, but it doesn’t translate to specialisations such as front-end/UX/UI design and accessibility, client-side architecture and state management, data processing and consumption, machine learning, network programming, system operations, developer tooling etc. Most engineers will have one or two of these areas that they are passionate about and allowing them to become the subject-matter experts within your team or organisation is an equally compelling story for their personal development.</p>

<p>Most mature organisations will have some form of career path matrix that aligns completely across the entire business. Creating such a matrix is key to ensuring fairness in terms of compensation and benefit across all career paths within your organisation, and enables staff to understand levels of seniority. Mapping this matrix to your already defined job specifications then provides clear communication of the qualifications and expectations of each role, and how an individual might then change role or career path within it—even if they are jumping from being a junior sales person to a junior developer or vice versa. The key is to ensure your employees aspirations are only limited by their own choices and commitment, and that there is clear definition of requirements to support a move in any direction they choose.</p>

<p>Once you have done this, I recommend you map clear open salary bands to each level within your career matrix. The aim here is to make all salaries ultimately visible, thus limiting any potential variation that is the antithesis of diversity within a business and focusing very clearly on building trust with all employees. The best organisations have public salaries, because individuals are paid fairly within understood banding that maps to the requirements of their roles and responsibilities. Unfortunately, this isn’t easy to achieve, and requires constant market management to avoid problems of limited flexibility during new hire salary negotiations, and internal salary adjustments. Despite this, it is my personal belief that this model should be the aim of any mature organisation. The management effort is outweighed by the trust and engagement it inspires within the team, and it completely nullifies any whispered politics around pay.</p>

<h2 id="understand-the-needs-of-the-team">Understand the needs of the team</h2>

<p>The next thing to understand is the structure of your teams, and how you intend supporting cross-functional development and support. Often this will depend on the methodologies you are intending to use for project/programme management, with team design evolving organically from the way your business handles the flow of work from inception through to delivery.</p>

<p>By “team design”, I specifically mean how many teams you have, how many people are on those teams, what their individual roles are, and what those teams are going to be responsible for. Ownership and accountability will be defined by this, so it’s important you give it a fair amount of your time unless you’re able to grow an ownership model organically as your business grows. Disclaimer: This task can be really difficult. I have failed at this even recently, and retrospectively I think the changes I needed to make happen were outside the remit of my role—I needed to work more intensively with the wider business to achieve a fundamental change to the business operating model which could support a more successful organisational design within Engineering.</p>

<h3 id="function-vs-product-focus">Function vs. product focus</h3>

<p>In 1967, a programmer named Melvin Conway introduced the following idea (now known as Conway’s Law):</p>

<blockquote>
  <p>organizations which design systems … are constrained to produce designs which are copies of the communication structures of these organizations.</p>
</blockquote>

<p>To translate into slightly less impenetrable language:</p>

<blockquote>
  <p>Any piece of software reflects the organizational structure that produced it.</p>
</blockquote>

<p>A study of multiple large codebases was undertaken at Harvard Business School to validate this particular law. The study took multiple examples of software created to solve a particular problem (e.g. word processing, financial management etc.), and compared the codebases of loosely-coupled open source teams, and those of tightly-coupled teams. They found that the often co-located, focused product teams created software that tended more towards tightly-coupled, monolithic codebases. Whereas the open source projects resulted in more modular, decomposed code bases. This illustrates the need to design your organisation backwards from how you wish to deliver code.</p>

<p>Having worked in several larger organisations, its interesting to me that the ones with the greater success of consistent delivery are those that allow autonomy within their product and engineering divisions based on direct access to customers. Amazon, as an example, encourages a technical leader to treat his organisation as its own start-up, creating an environment where a team is forced to consider their users as customers, even if they are internal, and to plan and deliver their roadmap accordingly. In addition, operational performance is constantly measured and assessed using specifically identified key metrics for each subdivision. You cannot have function-focused teams working for a customer/product driven business unless there is some form of further adaptation in place which understands how to divide work for each function.</p>

<p>Tech start-ups, on the other hand, are often intensely product-focused due to growth around a limited use-case or customer cadre. In this case, it is more likely that the team will make the mistake of becoming too focused on the needs of one specific big customer, in order to keep the business. This can result in a loss of grip on the boundaries of a product or service, or worse, it turns the team into an outsourced pseudo-agency development resource for that one controlling customer. Strong product management is important here, but that product management needs to be the adapter between customer demand and intelligent technical delivery. Knowing how to convert requirements into user stories that make sense for functional teams is an undervalued skill. However, that’s a topic for another time.</p>

<h3 id="avoid-skill-silos">Avoid skill silos</h3>

<p>Enabling autonomy in a team requires a reduction in the opportunities for blockers. Back in the dark ages we suffered through a divide between ops, back-end, front-end, and QA skills. By grouping teams by skills we created artificial walls between stages of development and delivery. This enforced waterfall working—even though we <em>claimed</em> to be agile—because we had to wait for dependencies to complete further down the stack. The end result was that iterations were focused more on getting work over these boundaries, rather than rapid feedback loops with users.</p>

<p>In my opinion, development teams perform better when they are truly cross-functional. However, it is also important to realise that no two cross-functional teams will be exactly the same. Cross-functionality comes from understanding that a good team is organically built-up around the skills of its members. If we imagine each skill “specialisation” as a circle in a gigantic Venn diagram, each team member will appear on that diagram in quite different places, dependent on their key specialisations and competence in other areas. With that in mind, it makes sense to balance skills using complimentary team members, allowing for some degree of overlap. If I do not have the skills to complete delivery of a specific task, it is important that I can rely on another member of my team to support me through it. A team of complimentary peers is a powerful thing, especially if each team member has a little imposter-syndrome—this is a sure sign they’re in an environment of learning and growth, supported by everyone around them and not just their mentors or leaders.</p>

<p>This also relates to the concept of “full-stack” engineers—or what Amazonians often call <em>fungible engineers</em>. These are engineers that are equally capable across the entire stack—from the toughest cross-device-and-browser front-end challenge, through API and system architectural separation woes, to the gnarliest operation tooling problem—therefore making them fungible or flexible to move around, solving the business problems with the highest priority. In my opinion, however, this is a recruitment-driven misidentification that belittles the unique talents and experiences of each individual. I have an entire other post in progress on this subject. There are plenty of jack-of-all-trades developers, but they will always have a tendency towards that one particular specialisation. Which means they are actually unlikely to be “fungibly” valuable (otherwise described as flexibly valuable) across a wide array of problems, and are far more likely to create more issues than they solve. Any capable engineer knows what it is to grow through iterative failure; to learn from their mistakes, and to lead others with this invaluable knowledge. The process of doing this will always result in a specifically targeted skill-set. Also, I believe any truly self-aware engineer understands the effect their team has on them as an enabler. As previously stated, it is cross-functional <em>teams</em> that become flexible. Do not move individuals between problem spaces; move the entire team. This means you gain all that valuable talent and working culture without having to rebuild relationships between team members.</p>

<p>An additional method to avoid skill silos in teams is to encourage cross-team expertise, either as working groups—where individuals in a team also work with like-minded specialists in other teams to create standards and improve quality—or as satellite teams who are specifically designed to provide support in a given proficiency alongside any team that needs it for a given deliverable. My best experience with this has been in testing, where a “roaming” team of test-automation engineers spend time seated with a given team, helping them ramp up their skills and quality standards before moving on to another team. I have also seen this employed as “tiger teams”, who are a cross-functional team with significant maturity who may not have any one specific area of ownership, but can be deployed to help solve high priority problems within your entire stack. This is the absolute peak of an effective cross-functional team, as spoken about before.</p>

<h3 id="team-size">Team size</h3>

<p>Despite being the topic of great debate, I believe Amazon have significant cultural maturity, driven in no small part by Jeff Bezos’s own pearls of wisdom. A good example is the “two pizza team” rule, which advises not to have any teams larger than can share two pizzas together. This rule is based entirely on the rapidly increasing number of relationships between individuals that need to be subconsciously managed with each added member of the team. This can be modelled with the equation:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>l = n(n-1)/2
</code></pre></div></div>

<p>And if we visualise that with a graph:</p>

<p><img src="/assets/img/two-pizza-team-relations.svg" alt="A visualisation of the logarithmically scaling number of relations in comparison to the number of team members." /></p>

<p>Not only do larger team sizes make for significantly greater relationships to manage, but they have also been proven to make people overconfident. Teams have a tendency to increasingly underestimate task completion time as their size grows, due to the optimism of the group. In their paper, “<a href="https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.230.7912">The Team Scaling Fallacy</a>”, Bradley R. Staats, Katherine L. Milkman, and Craig R. Fox observe that when tasked to build the same Lego kit, teams of two people took 36 minutes while teams of four took 52 minutes to finish. However, the larger teams were almost twice as confident about how long they’d take. That kind of error in estimation can be extremely costly for a growing business or team.</p>

<p>In my experience, the sweet spot is between 5-8 folks, but opinions differ—even within Amazon itself. Based on the equation (and graph) above, 8 folks is a maximum of 28 relations to maintain between the individuals in the team, which makes for about the right balance between delivery speed, accuracy of estimation, and efficient communications. At this point, if you need to scale further, add another team and divide up the problem-space so that each team can have very specific ownership, control, and accountability.</p>

<h3 id="seniority">Seniority</h3>

<p>The other question I am asked a lot is, “what does a good team make-up look like in terms of seniority?” Unfortunately, there’s no single answer to this. It really does depend on the people. As an aside, it is my opinion that seniority is usually contextual to a team and business anyway, and those that are considered senior in one company and role are unlikely to be senior in their next role. However, they will have a greater <em>potential</em> to excel and will likely rise in seniority faster than similar peers who have not been senior before.</p>

<p>So what is seniority? Basically two things:</p>

<ol>
  <li>Autonomy; the less guidance an individual needs in applying themselves to delivering team and company goals (without creating confusion or ambiguity), the greater their seniority within a team.</li>
  <li>Altruism, support, mentoring; accepting that seniority relates to greater autonomy, it follows that more senior folks spend more time working with team members that need more guidance and support. Senior team members invest significant effort in making the whole team better at what they do.</li>
</ol>

<p>It is also worth noting that seniority at one employer—in one position—is very specifically contextual. There should be no expectation to transfer seniority, earned through experience or longevity, to a completely different role and company. Seniority needs to be consistently demonstrated through action. With that in mind, it is important as a hiring manager to make real use of a probation period to ensure a new hire is meeting your expectations. This really isn’t something you can confirm simply through interviews alone.</p>

<p>In terms of team structure, my personal preference is to have one or two senior folks per two-pizza team. However, I can’t emphasise enough how important it is to ensure those two folks are mutually complimentary. Having two senior folks on a team who are often at odds with one another is going to be one of the most destructive things you can do to your business. The major aim of any team structure design is to ensure that every member is complimentary to their peers, and that each individual brings something new and lifts the performance of the team as a whole. With senior folks, this effect is obviously going to be even more impactful as they will spend more of their time mentoring those with less autonomy.</p>

<p>As another aside, whilst I was writing this post over the past few weeks I came across this great and relevant post on an anonymous blog/newsletter called LittleBlah (whoever you are, I’m loving your work). Needless to say, I’ve subscribed:</p>

<p><a href="https://littleblah.com/post/2019-09-01-senior-engineer-checklist/">A Senior Engineer’s CheckList</a></p>

<p>The right make-up of seniority across your teams is largely going to depend on how urgently you need deeper hands-on experience (like managing operational systems in production, as an example) vs. whether you have the flex to grow a team’s experience and skills organically over time. In my experience, organically grown teams perform better 80% of the time because they have developed together over time, and are more able to second-guess their colleagues and team mates. In comparison, if you hire too many senior level folks too early, you may have problems of contention and disagreement over the best ways to solve certain problems. It’s also worth noting that hiring more senior folks is going to take time, so you may not be able to have one or two per team at any given moment. In this situation, you need to ensure the senior folks are given flexibility to work at mentoring across all teams.</p>

<p>All that said, I’ve worked in very successful teams of both types. I do not think there is any one correct answer here, but I would always favour less senior roles and more entry-level. There are always more entry-level folks than seniors over time, and it’s incredibly rewarding to take folks on and help them “level up” before such time as they choose to leave your employment, for whatever reason. It doesn’t matter what your business is, or what you’re trying to achieve; ultimately it should always come back to the people you employ, and doing right by them. In many ways you’re setting an example as to how you expect <em>them</em> to treat other people, which will include your customers or clients too.</p>

<h2 id="understand-the-needs-of-the-company">Understand the needs of the company</h2>

<p>So now we understand the needs of the individuals we’re hiring, and the roles and team structures we’re hiring them into. We’ve also figured out that we need to be able to translate customer/product requirements into a set of well-bounded ownership teams with specific deliverables. But what about ensuring the teams are adding true value to the company? And how can we ensure we’re attractive and engaging as an employer? This is where company culture becomes important.</p>

<p>Many large organisations spend time defining the characteristics and culture they think make them successful, and share them publicly. This is an important tool in allowing current employees to understand what the company is expecting of them, but also in attracting new employees. A few good examples are:</p>

<ul>
  <li>Netflix: <a href="https://jobs.netflix.com/culture">https://jobs.netflix.com/culture</a></li>
  <li>Amazon: <a href="https://www.amazon.jobs/en/principles">https://www.amazon.jobs/en/principles</a></li>
  <li>Facebook:<a href="https://www.facebook.com/careers/facebook-life/">https://www.facebook.com/careers/facebook-life/</a></li>
</ul>

<p>The folks over at <a href="https://tettra.co/culture-codes/culture-decks/">Tettra have also collated a whole bunch of culture decks here</a>.</p>

<p>At a bare minimum, you should think about defining out a <strong>business summary</strong>, <strong>vision statement</strong>, and <strong>mission statement</strong>; even if you’re only generating them for a single internal ownership team. These will help you formalise the language and imagery you use to describe what you do, and what you’re trying to achieve as an ownership group. This also helps unify these ideas across all your team members, which is super important if you want them to work as a coherent delivery organisation.</p>

<p>This stuff can sound very “soft and fluffy” (for want of a better description) to development teams, which means they often overlook the immediate value. Believe me, I have never delivered this information to a team and not received feedback that they had somehow misconstrued what they were building, or that it had somehow bridged the gaps in their understanding. People like to have a strong grasp on what it is they’re doing day-to-day. Literally anything we can do to help formalise or realise that should be considered priority.</p>

<p>In the longer term, setting out a set of standard behaviours or values for the team will prove to be an important group task. It can be the difference that enables confident decisions and strong plans and avoids confusion and ambiguity. Moreover, it helps provide team identity which affects our sense of belonging, as discussed way back in Maslow’s Hierarchy of Needs.</p>

<h3 id="key-performance-indicators">Key Performance Indicators</h3>

<p>Another important tool in helping a team understand their place in the wider business are <strong>key performance indicators</strong>. At their most basic, these are a set of 1-3 metrics that the team agree will be used to measure their success. It’s important these metrics are;</p>

<ul>
  <li>well-defined and quantifiable;</li>
  <li>fundamental to achieving the team or organisation goals;</li>
  <li>applicable specifically to the teams affect on the business needs;</li>
  <li>communicated throughout the organisation <em>and</em> the team.</li>
</ul>

<p>At a higher level, it’s usually better to ensure there are KPIs defined at the business level, and that they are then repeated and transformed down to more suitable KPIs for each team within the business.</p>

<p>Once these metrics have been decided on, the team should then set about constantly measuring and reporting on them, allowing an iterative feedback and adjustment loop. The sooner a team have this sort of process in place, the sooner they will be able to both grow in effectiveness, but also to learn from their mistakes and share that knowledge with the wider organisation.</p>

<p>All this said, I have personally found that trying to wrestle KPIs all the way down to the personal level is a lost cause. Personal goals can certainly reflect the premise of a particular KPI, but they need to be individually tailored to personal growth, rather than that of the business. KPIs provide leadership and direction to teams, but they are difficult to deliver against for individuals, who should be working to a slightly different but complimentary agenda.</p>

<h2 id="summary">Summary</h2>

<p>So if you want to build better teams, you have a bunch of things to think about and deliver yourself:</p>

<ol>
  <li>Generate a business summary, mission statement, and vision statement.</li>
  <li>Build a career matrix showing career paths and job specifications.</li>
  <li>Balance the skill and seniority split of your two-pizza teams.</li>
  <li>Figure out the ownership of those teams, to support the architecture of your product.</li>
  <li>Work together to come up with some company values.</li>
  <li>Define business and team level KPIs.</li>
</ol>

<p>Generally, you’ll find once you’ve got all this sorted out, it will be much easier to sell your culture and brand during hiring activities, and your team will naturally attract like-minded individuals. By representing the best interests of the individuals, they are more likely to talk favourably about you as an employer in social situations which will spread through networks quickly.</p>

<p>In addition, by having this all sorted out in your own head, it becomes easier to provide documentation and points of reference for your team. This means they will feel better supported in their growth, and are therefore likely to be more engaged over time.</p>

<p>This is, of course, only the start. Once you’ve got this all worked out, you’re going to need to start writing performance profile job specifications; figure out a sensible interview process that allows you to identify technical skills, autonomy, altruism, experience, and anything else you come to value; and design a probation process and ongoing scheme of 1:1s that provides the right environment for goal setting and support, allowing your employees to grow significantly during their tenure with you and your business. But that’s a whole other blog post really, and I’ve already taken up enough of your time.</p>

<p>Finally, and unashamedly, if you like the sound of the above and you’re a React/RoR developer, and you’d like to come work with me at Higher in Perth, WA, by all means <a href="https://www.linkedin.com/in/timhuegdon/">reach out to me via LinkedIn</a>.</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[How agile is your backlog?]]></title>
        <link href="https://nefariousdesigns.co.uk/how-agile-is-your-backlog.html"/>
        <updated>2019-04-09T23:05:00+08:00</updated>
        <id>https://nefariousdesigns.co.uk/how-agile-is-your-backlog</id>
        <content type="html"><![CDATA[<p><img src="/assets/img/undraw_task_31wc.png" alt="" /></p>

<p>Software developers like lists. They like to log-on and focus on working their
way through a list of deliverables, checking them off one-by-one as completed.
Developers like it even more if they are given clear requirements for each of
those deliverables, because having to dig up or define your own requirements
requires context switching away from development. Context or task switching away
from development is a form of process waste—see my previous post, “<a href="https://nefariousdesigns.co.uk/eliminating-web-development-waste.html">Eliminating
Web Development
Waste</a>“—and
software developers do not like wasted time.</p>

<!--more-->

<p>When we adopt an agile process for software development, the product backlog
becomes the list of things to complete. It is at this point I often see
developers exhibiting frustration because the backlog is no longer as clear as
the to-do list they had made for themselves. When faced with this frustration,
my advice is to remember that the backlog is a list of work items for <em>greater</em>
audiences than the development team.</p>

<p>The backlog provides a product source-of-truth for everybody; from sales
through to support. Each item in the backlog needs care and attention to
ensure it is easy to read, contains all relevant reference materials, and
provides enough explanation that anyone in the business can understand the
user need and the proposed solution. That said, it’s also important that
everyone accepts that each item in the backlog is a work in progress, and
that gaps should be acknowledged (but filled in as soon as possible). Being
agile means we should recognise it is a pipe dream to expect perfect
requirements for every user story or task we undertake. Change is inevitable,
and the agile manifesto acknowledged that when it stated:</p>

<blockquote>
  <p>Customer collaboration over contract negotiation<br />
Responding to change over following a plan</p>
</blockquote>

<p>Over the past few years, I’ve worked with a few businesses that have started
down the agile path for the wrong reasons. They believe it will make them
faster, because they’re delivering incrementally. Inevitably, these businesses
then get into all sorts of issues because they fail to adapt their processes
to allow clear conversation between the actual users and the developers. Agile
is not about speed of delivery but speed of <em>correction</em>, and every layer of
business function between the folks using the software and the folks designing
and building it is a layer of misdirection in that correction.</p>

<p>The whole point of iterative development and incremental improvement is that we
have a shorter feedback loop. We avoid veering off course from the user’s
requirements and deliver small improvements, instead of one massive release that
somehow lost its way and missed the brief. What’s more, good feedback requires
direct exposure to users, who can tell us whether we’ve hit the brief or whether
we’ve missed something.</p>

<p>Which brings me back to the backlog being a list of stuff to do. Being agile
also means recognising that one user-story or epic does not have to be the
final word for a given feature. Stuff gets missed. Stuff ends up broken. It is
entirely acceptable to create further tasks and stories to patch stuff up, even
if we’ve already delivered an epic for that feature. The best agile backlogs are
made up of a lot of tiny deliverables with very simple acceptance criteria that
help us avoid over-engineering but that iteratively build up to a whole that is
greater than its parts. Write your stories and tasks to deliver value against a
clear user need, but with the minimum viable acceptance criteria. Anything else
can come later.</p>

<p>So next time you’re irked about the backlog, remember:</p>

<ol>
  <li>It’s not just for you; it’s for everyone, including the users.</li>
  <li>It’ll work better if you keep user stories and tasks simple and direct.</li>
  <li>Improvement between iterations requires feedback and conversation with
everyone, <em>including the users</em>.</li>
</ol>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Adding SSL/TLS with CertBot]]></title>
        <link href="https://nefariousdesigns.co.uk/adding-ssl-slash-tls-with-certbot.html"/>
        <updated>2018-10-17T13:08:00+08:00</updated>
        <id>https://nefariousdesigns.co.uk/adding-ssl-slash-tls-with-certbot</id>
        <content type="html"><![CDATA[<p>Security is essential for the modern internet. In order to ensure connections
stay secure across the information superhighway, it’s a good idea to implement
SSL/TLS on your web servers—even when they’re only serving mundane musings like
this blog.</p>

<p>Secured connections require a certificate, which needs to be issued by a trusted
third-party certificate authority (CA). This used to be costly and slow and
required a great deal of manual jiggery-pokery. However, thanks to Let’s
Encrypt, a free automated CA, obtaining certificates for SSL/TLS is now very
easy indeed.</p>

<p>With that in mind, let me walk you through activating SSL/TLS for your web
server using CertBot, an automated tool that will implement SSL and regularly
update the required certificates via Let’s Encrypt.</p>

<!--more-->

<h2 id="certificates">Certificates</h2>

<p>The SSL/TLS certificate verifies and creates secure sessions between client and
server over the SSL protocol. This secure connection cannot be established
without the certificate, which digitally connects company information to a
cryptographic key. Certificates are issued by a Certificate Authority, who
certify ownership usually through payment and then a further validation process
against the domain in question. However, these days there is a better option.</p>

<h3 id="lets-encrypt">Let’s Encrypt</h3>

<p><a href="https://letsencrypt.org">Let’s Encrypt</a> is a free, automated, and open
[certificate authority, run for the public’s benefit. It is a service provided
<a href="https://letsencrypt.org/isrg/">by the Internet Security Research Group (ISRG)</a>,
[and they issue certificates for free simply because they believe in a more
[secure internet for everyone.</p>

<p>It’s worth noting that Let’s Encrypt only issue Domain Validation (DV)
certificates, and not the more secure Organisation Validation (OV) or Extended
Validation (EV) certs as issuance is more complicated for these. Be sure to
understand the difference between these certificate types because you may well
do better implementing the alternatives for more trust in your business. There’s
<a href="https://www.ssl.com/article/dv-ov-and-ev-certificates/">a good explanation of the differences between certificates over at
SSL.com</a>. There’s also a
great explanation of <a href="https://letsencrypt.org/how-it-
works/">how Let’s Encrypt works</a> over on their site, so I won’t waste too much time on it here. In short,
by making the issue of DV certificates free, the ISRG have made the entire
process of implementing SSL/TLS on your servers almost painless.</p>

<h2 id="certbot">Certbot</h2>

<p><a href="https://certbot.eff.org/">Certbot</a> is an easy-to-use automatic client for Let’s
[Encrypt that fetches and deploys SSL/TLS certificates for your webserver. If
[you’ve ever undertaken the manual struggle of certificate management, Certbot
[will be a breath of fresh air.</p>

<p>As a workflow, you simply install Certbot on your server, run through a short
configuration process to identify the sites you wish to turn SSL/TLS on for, and
then it will do all the hard work requesting certificates, installing them,
setting up your webserver configuration, and restarting the hosts. It’ll even
create redirects from HTTP to HTTPS if you want them. What’s more, it’ll keep an
eye on your certificates and update them when the time comes, so you almost
never have to think about it again.</p>

<h3 id="installation-and-configuration">Installation and configuration</h3>

<p>If you refer to <a href="https://certbot.eff.org/docs/">the Certbot documentation</a>, they
have walkthroughs for common cross-sections of webservers and hosts. In my case,
I was working with Ubuntu Bionic and Nginx:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">sudo </span>apt-get update
<span class="nv">$ </span><span class="nb">sudo </span>apt-get <span class="nb">install </span>software-properties-common
<span class="nv">$ </span><span class="nb">sudo </span>add-apt-repository ppa:certbot/certbot
<span class="nv">$ </span><span class="nb">sudo </span>apt-get update <span class="nv">$ </span><span class="nb">sudo </span>apt-get <span class="nb">install </span>python-certbot-nginx
</code></pre></div></div>

<p>This got Certbot installed on the host, and then all I needed to do was kick-off
the configuration process for Nginx:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">sudo </span>certbot <span class="nt">--nginx</span>
</code></pre></div></div>

<p>Certbot will then ask which sites you want to activate SSL/TLS for in your Nginx
configuration, will reach out to Let’s Encrypt to get certificates and install
them, update your Nginx configuration, and restart the Nginx service.</p>

<p>If you’re a little more precious about your Nginx configuration files, Certbot
can be directed to only obtain certificates with the following command:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">sudo </span>certbot <span class="nt">--nginx</span> certonly
</code></pre></div></div>

<p>Obviously, you’ll then need to update your Nginx configuration yourself.</p>

<p>At this point you have successfully set-up your site(s) for SSL/TLS and can
happily go about your day, safe in the knowledge your users’ connections are
encrypted.</p>

<h4 id="automatic-renewal">Automatic Renewal</h4>

<p>The Certbot packages also installs a cron job that will renew your certificates
automatically before they expire. This is a great feature because Let’s Encrypt
certificates last for only 90 days.</p>

<p>You can <em>test</em> automatic renewal for your certificates by running this command:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">sudo </span>certbot renew <span class="nt">--dry-run</span>
</code></pre></div></div>

<h4 id="wildcards">Wildcards</h4>

<p>It’s also possible to have Certbot obtain a wildcard certificate that will also
cover all subdomains for your domain. However, this requires installation of DNS
plugins and use of their ACMEv2 server. You can find information about how to do
all this in the <a href="https://certbot.eff.org/docs/">excellent Certbot
documentation</a>.</p>

<h2 id="summary">Summary</h2>

<p>As you can see, going the extra mile for your users and encrypting their
connections is actually pretty painless when you adopt Certbot and Let’s
Encrypt. Hopefully this short post will help a few folks get over the fear of
implementing SSL/TLS, and help to ensure more of the web is secure!</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Writing again]]></title>
        <link href="https://nefariousdesigns.co.uk/writing-again.html"/>
        <updated>2018-10-13T12:56:00+08:00</updated>
        <id>https://nefariousdesigns.co.uk/writing-again</id>
        <content type="html"><![CDATA[<p>*tap tap tap* Is this thing on? Wow. Is it really six and a half years since
my last post on here? I <em>really</em> need to get back on the horse.</p>

<p>In a recent conversation with a bunch of old web development and design friends,
discussion got around to lamenting that a bunch of us seem to have stopped
writing posts and articles on our personal blogs. With that in mind, I’ve
decided to resurrect this old thing and start writing again.</p>

<p>In many ways, <a href="https://thewatchmakerproject.com/slight-return/">Matthew Pennell’s “Slight Return” post</a>
(potentially an artefact of the same conversation mentioned before) really
resonated with me. I believe one reason for my being AWOL is the fact that each
of my articles took a great deal of commitment. I would spend a lot of time
double checking my sources, and crafting my tutorials, deeply aware of the
intelligent scrutiny of my peers. Five years later, and I realise that there is
just as much value in the simple personal gratification of documenting stuff
I’ve been playing with, so that is probably mostly what I am going to do.</p>

<p>First things first, though, I need to enable some HTTPS on this baby.</p>

<p>Which gives me a great idea for the next post…</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Eliminating Web Development Waste]]></title>
        <link href="https://nefariousdesigns.co.uk/eliminating-web-development-waste.html"/>
        <updated>2012-05-28T09:02:00+08:00</updated>
        <id>https://nefariousdesigns.co.uk/eliminating-web-development-waste</id>
        <content type="html"><![CDATA[<p>The concept of waste within web development might seem reasonably clear to most managers and developers, however in my experience it is something that most teams need help to identify. I’ve recently worked with a team who became exceptionally good at identifying waste and, as a result of this alongside a whole swathe of other techniques, were by far the most efficient agile team I’ve ever worked with.</p>

<p>Eliminating waste is the first—and most fundamental—principle of <a href="http://en.wikipedia.org/wiki/Lean_software_development">Lean Software Development</a>; something that was introduced to me by an exceptionally talented Project Manager whom it was my pleasure to work with. Lean Software Development is a set of seven fundamental principles that really work hand in hand with agile development to improve software delivery. Those principles are: eliminate waste, amplify learning, decide as late as possible, deliver as fast as possible, empower the team, build integrity in, and see the whole. In this article I’m going to look at how we can improve our ability to identify waste and iteratively remove it from our development chain.</p>

<!--more-->

<h2 id="lean-manufacturing">Lean manufacturing</h2>

<p>The principles of Lean Software Development are basically reinterpretations of the principles of Lean Manufacturing as designed and tested by <a href="http://www.poppendieck.com/people.htm">Mary and Tom Poppendieck</a>. Those original manufacturing principles—formulated by Sakichi Toyoda, the founder of Toyota Industries, and his son Kiichiro Toyoda, the founder of the Toyota Motor Corporation—were realised as an actual method of production by the Toyota engineer Taiichi Ohno. This later came to be known as both Just In Time Manufacturing and the Toyota Production System.</p>

<p>Lean Manufacturing is a production practice that considers the expenditure of resources for any goal other than the creation of value for the end customer to be wasteful, and thus a target for elimination. Working from the perspective of the customer who consumes a product or service, “value” is defined as any action or process that a customer would be willing to pay for. At its most simple, Lean Manufacturing can be considered a move towards manufacturing to order rather than manufacturing to build stock since stock is essentially waste.</p>

<p>In reading descriptions of American supermarkets, Ohno saw the supermarket as model for what he was trying to accomplish in the factory. A customer in a supermarket takes the desired amount of goods off the shelf and purchases them. The store restocks the shelf with enough new product to fill up the shelf space. Similarly, a Toyota work-center that needed parts would go to the inventory storage point for the particular part and withdraw the quantity it needed. The storage point would then be restocked by the work-center that produced the part, making only enough to replace the inventory that had been withdrawn.</p>

<h3 id="the-toyota-production-system">The Toyota Production System</h3>

<p>The key objective of the TPS was to design out overburden (muri) and inconsistency (mura), and to eliminate waste (muda). A manufacturing process that removes inconsistency is capable of delivering smoothly. However, that process also needs to be as flexible as possible so as not to introduce overburden which creates waste. Also there is clear value in the elimination of waste in any process.</p>

<h4 id="tps-reports">TPS Reports</h4>

<p>Anyone who’s worked in the industry for a while, <a href="http://youtu.be/0flsg4GMQxQ">or has seen the film Office Space</a>, will be familiar with the term “TPS reports” being synonymous to pointless paperwork. TPS reports have nothing to do with the Toyota Production System, the TPS stands for “<a href="http://en.wikipedia.org/wiki/TPS_report">Testing Procedure Specification</a>”.</p>

<p>That being said, TPS reports as pointless paperwork is entirely relevant as waste that could be removed from your processes. We’ll come back to that later.</p>

<h2 id="web-vs-software-development">Web vs. Software Development</h2>

<p>Before we get too involved in investigating the waste element of this post, let’s just examine the difference between general software development and web development:</p>

<p>I consider myself to be a web developer and a web development manager. I am used to working with the internet as part of my development landscape and also as part of my toolkit. This means I am used to dealing with high numbers of users, a vast array of user-agents which interpret my code and therefore need to be tested against, a degree of uncertainty as to the capabilities of the user-agents and the users themselves, and a wide number of technologies. This has been described by <a href="http://en.wikipedia.org/wiki/Douglas_Crockford">Douglas Crockford</a>—the inventor of JSON, and often described as the godfather of JavaScript—as the “most hostile environment imaginable”.</p>

<p>This is not to say that software development is any less hard or varied, just that there are a number of specific complications put on me as a web developer; and there are a number of very specific web-sourced problems that I’m used to solving. It’s simply different because it specifically involves the epic WAN that is the Internet.</p>

<p>Lean Software Development translates very well when dealing specifically with web development since the same problems exist in both development life-cycles. What really varies is how we might implement a solution to those problems. Taking that into consideration, be aware that I’m writing this article as a manager of web developers <em>not</em> as a manager of software developers.</p>

<h2 id="waste-in-web-development">Waste in Web Development</h2>

<p>The TPS identifies seven types of <em>manufacturing</em> waste:</p>

<ol>
  <li>Overproduction</li>
  <li>Waiting</li>
  <li>Transportation</li>
  <li>Extra processes</li>
  <li>Overstock</li>
  <li>Motion</li>
  <li>Defects</li>
</ol>

<p>In relation to <em>software development</em>, however, it’s clear that not all these types of waste translate. Lean Software Development identifies the following types of waste which translate perfectly between software and web development:</p>

<ol>
  <li>Partially complete work</li>
  <li>Extra processes</li>
  <li>Extra features</li>
  <li>Task switching</li>
  <li>Waiting</li>
  <li>Motion</li>
  <li>Defects</li>
</ol>

<p>Since some of those are not immediately clear as waste, let’s examine them in more detail…</p>

<h3 id="partially-complete-work">Partially complete work</h3>

<p>It’s fair to say that <em>all</em> web development is partially complete at some point in its lifecycle. The priority here is to minimise the <em>amount</em> of partially complete work that is within a project at any given moment.</p>

<p>Partially done web development can quickly become obsolete as it is replaced with a differing method or solution. The only way to be sure what problems exist in a piece of code are to have it fully integrated with the rest of the project. If you are working behind feature branches or feature toggles, or some other method for cloistering partially done work, you are suffering from your isolation as much as you are benefiting from it.</p>

<p>In fact, the only place where you will capitalise on your investment in a feature is when it is in production. Partially done development ties up resources in investments that have yet to yield results. You need to provide integration test coverage, end-to-end test coverage, integration code, and a whole host of other methods of ensuring the minimum of bugs exist when you finally release it from its isolation. If your feature never actually <em>makes</em> it to production, you have some significant investment to write off. Reducing the amount of partially complete work within your project is both a reduction of waste <em>and</em> risk.</p>

<h3 id="extra-processes">Extra processes</h3>

<p>We all love our processes and documentation, right? I’d be willing to bet that just about everyone who has worked in an agile organisation of some form has become disillusioned with the amount of meetings or breaks from focus they have to attend as agile “ceremonies”, and the added work dealing with documenting user stories, their requirements, and how they might be tested and accepted. In fact, two of the tennets of <a href="http://agilemanifesto.org/">the agile manifesto</a> are specifically related to process and documentation:</p>

<blockquote>
  <p>We have come to value:</p>

  <ul>
    <li>Individuals and interactions over processes and tools</li>
    <li>Working software over comprehensive documentation</li>
  </ul>
</blockquote>

<p>At every opportunity you should be assessing whether a particular process or document is entirely necessary for your development. Extra processes and documentation consume resource, slow down response times, and can mask problems elsewhere. What’s more they break focus, which is something I’ll come back to when I explain “motion” as a type of waste.</p>

<p>Many development processes require paperwork of one form or another. Most of the companies I’ve worked for recently have replaced actual hard-copy with wiki documentation these days, but those documents are still there. Documents for release processes, documents for sign-off, documents for traceability, not to mention documentation for security or compliance.</p>

<p>The real test of these documents is whether someone is actually waiting for it as a deliverable, and whether it then adds value to <em>their</em> process. If not, dump it. Otherwise, find ways to simplify that process. Reduce the amount of input required by using templates or pre-designed input forms. Condense the amount of information required. In fact, there should always be an ongoing process of refinement and efficiency evaluation for all documents and processes. Any required process should be as efficient and effective as possible. Rapid yet easy to validate.</p>

<p>In terms of documenting code, do it as you go. Write clean, easily understandable, easy to maintain code and enforce style with static-code analysis and code reviews. Make sure code is commented effectively and you’ll cut down on cost. It’s important to remember that sometimes documentation is <em>required</em> for code when knowledge needs to be shared over a wide base, but if you’ve minimised what other documentation is required this will be the exception to the norm.</p>

<h3 id="extra-features">Extra features</h3>

<p>Adding in extra features to a piece of development is over-engineering; don’t do it. There will be many times that you foresee the need for an extra feature before you actually have the requirement. There are other times that a developer might see the opportunity to add something extra that may save time for others later on. Whilst at first glance this may seem relatively harmless and of benefit in the long run, it is almost always a source of waste.</p>

<p>All code in the system should be tracked, reviewed, tested, and integrated every time it is touched. What’s more it then needs to be maintained for the life of the project. With that in mind, it is important to remember that every bit of code adds complexity and a new possible point of failure. It also introduces something new for all the developers to understand and—worse—misunderstand and misuse.</p>

<p>If there is no requirement for a piece of code <em>now</em>, don’t write it. Putting it in is waste. Resist your urge to over-engineer.</p>

<h3 id="task-switching">Task switching</h3>

<p>The fastest way to complete two projects using the same people is to do it one at a time, sequentially. Trying to run two projects in parallel using the same resources introduces a large amount of waste. Likewise, sharing people between teams is also wasteful.</p>

<p>Much like extra process, task switching breaks focus. Every time a developer, QA, IA, or designer have to switch tasks, there is a fair overhead to pay. These sorts of tasks require enough focus to warrant a significant amount of time to get into “the zone” or “flow”. Thus, switching between tasks incurs waste through time.</p>

<p>Similarly, being a member of two teams introduces interruptions that might be entirely unrelated to the person’s current task. This means even <em>more</em> task switching, and probably at an even more granular level. For this reason alone it is unwise to assign people to multiple teams.</p>

<p>To illustrate how much task switching can affect delivery time, list 6 peoples names. Firstly, time how long it takes to write each name one after the other. Next, time how long it takes to write a letter of each in turn until you’ve written all 6 names completely. You’ll find the latter takes significantly longer than the former. This is only the simplest form of task switching and yet the waste incurred is quite clear.</p>

<p>Back in 2009, <a href="http://www.paulgraham.com/bio.html">Paul Graham</a> wrote a fantastic piece on focus entitled “<a href="http://www.paulgraham.com/makersschedule.html">Maker’s schedule, Manager’s schedule</a>”. In it he examined the difference between time schedules for developers and managers. It’s important that all managers understand that their schedule is significantly different to the developers that report to them.</p>

<p>A developer works in larger units of time than a manager, with much longer between breaks of focus; usually something in the region of a half-day unit. They dive into work as soon as they arrive at the office and will break focus at lunch. Likewise, when they return for lunch they’ll dive back in and only come back to the surface when it’s time to leave the office. Usually they’ll arrange their tasks in chunks that align to this and therefore will complete tasks shortly before lunch or shortly before they’re ready to leave for the evening.</p>

<p>Managers work in shorter units; usually around 1 hour in length. This allows time for meetings and context switches in between. As a manager it’s your <em>job</em> to context switch effectively, although even the greatest manager in the world will struggle to do it for too many subjects. This is why it’s important to make sure you don’t bite off more than you can chew in terms of projects to run. If you have, it’s time to start delegating.</p>

<p>If you’re a manager and you want effective makers, you need to arrange your days to suit them, not you. Allow 30 minutes in the morning for email checking and an added 15 minutes for the daily stand-up meeting. Don’t bother them again until directly before or after the break for lunch or at the end of the day. Trust me; they’ll cope with this much better than continuous interruptions throughout the day.</p>

<p>Likewise, if you’re a developer, be strict about what you do at these key times during the day. Make sure you don’t kick off development before your stand-up or you’ll fail to cope with the interruption. If people can’t agree to arrive at the office at around the same time in the morning, then you’ll be better off as a team scheduling the stand-up around lunchtime.</p>

<p>All this might sound obvious but you’ll be surprised how many teams let this sort of misalignment between team members screw up their daily flow. It’s also worth noting that the larger the team, the harder it is to align this stuff. There’s definitely a sweet spot to be found in team size and I personally believe it’s around 6-8 members.</p>

<h3 id="waiting">Waiting</h3>

<p>Day to day development is thick with delays. It’s a standard part of our working lives for projects to be delayed at the start, awaiting requirements or documentation; for the actual development to be blocked awaiting testing or deliverables from IA and UX; or to delay delivery through an inefficient release process.</p>

<p>In web development, delays can be a serious form of waste. They prevent the completion of work and they prevent the capitalisation of investment in the development itself. The speed at which we can respond to a customer-driven requirement is directly related to the number of delays in our development life-cycle.</p>

<p>As soon as we can accept that delays are a significant form of waste, we can identify where those delays occur and optimise them out of our processes. One of the seven principles of Lean Development is “decide as late as possible”. Taking that into account, it is better to re-prioritise tasks based on the delays you are likely to experience than suffer significant blockages in your delivery. This might mean putting tasks off until you have more information or free resource, or it might mean rearranging tasks so that developers are working on minimising those delays before delivering their original priority.</p>

<p>The most common delays in web development are when work passes between individuals. There’s nothing worse than finding out you’re prevented from completing a task because the wireframe or design hasn’t been completed or the requirements haven’t been finalised due to poor prioritisation. It is important that, as a team, you don’t agree to work on more than you can complete and similarly, it’s also important that you don’t agree to work on stories or tasks that have outstanding dependencies or requirements. Sometimes taking the time to groom your backlog as a team can mean the difference between wasting time on waiting or a user story or task flowing through your process painlessly.</p>

<p>Further to that, you can often reduce the time waiting for a deliverable by eradicating the deliverable altogether. I’ve had great success in the past by removing the need for wireframes and design visuals from the IAs and designers and getting them interacting with the developers on a regular basis. If the designers and developers maintain a clear style-guide with clear links to the front-end code—and at best a library of corresponding modules of code—they can easily relate new features to this through “pair programming” for an hour or two. Remove the requirement for a deliverable and you’re only left waiting for the developer and designer to have some time together in their calendars. This should be significantly easier to achieve since both parties are no longer required to deliver anything but their expertise during the interaction.</p>

<p>Finally, it’s important to remember that implementation is everything. If you can’t implement quickly following a key decision then you can’t <em>delay</em> that decision either. Empowering your team to deliver quickly and efficiently is your primary concern at all times, whether you are a manager or a team member.</p>

<h3 id="motion">Motion</h3>

<p>Agile software development favours colocation for teams. Likewise, the agile manifesto states that we should value customer collaboration; involving them in all discussions and decisions throughout the development process. The point of both these principles is the reduction of “motion” within the team.</p>

<p>It is important to make sure that developers, QAs, IAs, designers, product owners, project managers, and any other involved parties are immediately available to each other. Reducing the amount of time it takes for specific development-related questions to be answered is vital. Having everyone next to each other reduces that overhead.</p>

<p>If you can’t colocate people, the next best thing is to make sure they have easy communications as soon as they need them. Get everyone hanging out in a Jabber or IRC room, and make sure that’s as much a social experience as it is a work experience or they won’t come back. It should really imitate the local working environment so is likely to involve both work-related conversations and more water-cooler-type discussions and jokes. Expect that; nurture it; it’ll bring the team closer together.</p>

<p>It’s also important to remember that it’s good to put a name to a face. If some of your team are remote, make sure you get them over for social occasions once in a while. It’s good to break bread with your colleagues, and it’s easier to foster feelings of camaraderie when you’ve all been out to the pub together.</p>

<p>Similarly to social interactions, artefact interactions can also suffer from waste in motion. Reducing the amount of time it takes to pass a particular artefact of work from team member to team member can significantly improve the efficiency of the whole team. Good examples are the hand-off of design deliverables like style guides, wireframes, and visuals. Placing these in a known shared location using source control means all interested parties can have access to them immediately. Similarly, making sure tests are written and run in the same places regardless of whether they are written by developers or QAs means that there will be a clear vision of coverage for the whole team.</p>

<p>Motion might seem like a fairly inconsequential form of waste with a minimum of impact, but really it combines with task switching to be quite a serious problem. A competent team will work with this at a minimum from the outset, and most teams can address this issue quickly to improve their performance.</p>

<h3 id="defects">Defects</h3>

<p>Defects are an obvious form of waste, but really it’s only the undetected defects that cause a project to suffer. That might sound obvious at first, but it’s important to remember that the amount of waste generate by a defect is directly proportional to both the bug’s severity and the amount of time it goes undetected. A critical show-stopping defect that is identified and addressed quickly generates significantly less waste than a small insipid bug that hangs around for months undetected.</p>

<p>Reduce the impact of defects by finding them quickly through thorough testing practices and QA. Make sure the whole team are involved in that; quality is too important to be the responsibility of anyone <em>except the whole team</em>. Practices such as test-driven development and continuous integration can massively improve the time it takes to detect issues. It is important to understand what you are trying to achieve by adopting these practices and implement what you can.</p>

<h2 id="summary">Summary</h2>

<p>Understanding waste in your development process can help you improve the efficiency of your delivery. Being able to take the principles of lean development and integrate them into your agile teams are a clear way to improve your life as a manager. In my experience it’s almost impossible to implement agile within an organisation without truly understanding the whys and hows. Further to this, it’s everyone in the team that need to buy-in and understand, not just the managers or the organisation. This rings true for Lean Development as well.</p>

<p>This has really been a study of the types of waste discussed in <a href="http://www.amazon.co.uk/mn/search/?_encoding=UTF8&amp;x=0&amp;tag=gamersite-21&amp;linkCode=ur2&amp;y=0&amp;camp=1634&amp;creative=19450&amp;field-keywords=lean%20poppendieck&amp;url=search-alias=aps">the Poppendieck’s various books on Lean Software Development</a>. If you’re interested, I recommend you buy at least one of the various volumes. They’re absolutely worth it.</p>

<p>This is the first of a couple of articles I’ve started writing around agile and lean development practices and hopefully it’s at least got you thinking about how you can improve <em>your</em> life as a developer or manager. In the future I want to look at the complications around writing user stories, around implementing good testing practices, and how systems-thinking should be a primary goal of all teams.</p>

]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Flexible Responsive CSS Grids]]></title>
        <link href="https://nefariousdesigns.co.uk/flexible-responsive-css-grids.html"/>
        <updated>2012-03-28T21:47:00+08:00</updated>
        <id>https://nefariousdesigns.co.uk/flexible-responsive-css-grids</id>
        <content type="html"><![CDATA[<p>There are many ways to build CSS column grids; all of which have their pros and cons. In fact CSS3 has begun to implement a built-in model for columns which will be most useful in the future. However, until all the browsers our users surf the interwebs with are capable of this, we’ll have to rely on the good old CSS2 tricks to do it.</p>

<p>For a good while I used defined width floats for my grids. This means you have to calculate the width of each column and fix it (either with pixels or something more flexible like ems or percentages). That method is flawed due to rounding errors and general problems with flow when resizing. A better method is to use a mix of floats and negative margins for positioning. When I need to create a CSS column grid, I use this method.</p>

<p>However, when I was recently asked to share my method—which was outlined to me by a good friend and CSS guru—I had to remind myself how to do it. These are the perils of becoming a manager and developing less. In the interests of remembering next time (and also sharing the knowledge), I’ve decided to document the method in this article.</p>

<!--more-->

<h2 id="a-word-on-frameworks">A word on frameworks</h2>

<p>Just a quick word really. There are frameworks out there that will do your grids for you. I know they exist but I do not use them. Often they result in bloated mark-up and esoteric element identifiers that create unmaintainable code. Your mileage, of course, may vary.</p>

<p>I’m capable of creating a grid with the minimum possible code required. Hence, for production purposes, that’s what I do. In a prototyping situation, when I need something quickly and painlessly, I may choose to favour a framework; but it hasn’t happened yet.</p>

<p>If you choose to use a framework to set-up your grid, this article probably isn’t for you.</p>

<h2 id="source-order-is-important">Source order is important</h2>

<p>It’s good to make sure your main content is first in your source order. It’s helpful for accessibility, and it’s (a bit) helpful for SEO. This is something that isn’t always easy to enforce when using traditional grid techniques. The technique I use is actually built around this concept.</p>

<h2 id="building-the-mark-up">Building the mark-up</h2>

<p>The simplest possible mark-up we would want for a three column layout would be something like this:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;div&gt;</span>
    Main content
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div&gt;</span>
    Secondary content
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div&gt;</span>
    Navigation
<span class="nt">&lt;/div&gt;</span></code></pre></figure>

<p>To make it a little easier to target, and to make it a bit more readable, we can add some element identifiers:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"main container"</span><span class="nt">&gt;</span>
    Main content
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"related container"</span><span class="nt">&gt;</span>
    Secondary content
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"navigation container"</span><span class="nt">&gt;</span>
    Navigation
<span class="nt">&lt;/div&gt;</span></code></pre></figure>

<p>This gives us three containers for our columns. If we were to use the simplest possible method of floating each column left and fixing their widths, we’d have ourselves a column grid. However, that grid would not respond reliably cross-browser and could pick up wrapping errors. It also requires exact knowledge of the required width of ALL columns. Depending on how we’d like our grid to respond to change, this may be suboptimal.</p>

<h2 id="floats">Floats</h2>

<p>A floated element is shifted to either the left or right of its containing box and surrounding content then flows around it. Floating multiple boxes stacks them up either left or right, which is useful behaviour when attempting to simulate columns. However, if there is not enough horizontal room for the float, it is shifted downward until either it fits or there are no more floats present.</p>

<p>Floats are taken out of the <a href="http://www.w3.org/TR/CSS2/visuren.html#normal-flow">normal flow of the document</a>. This means the positioning model is changed somewhat and we can use that to our advantage.</p>

<h2 id="the-trick">The trick</h2>

<p>Applying a negative margin to a floated element allows us to control how it makes use of empty space around it. We can make use of this if we add an extra wrapper to our main content:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"container"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"main"</span><span class="nt">&gt;</span>
        Main content
    <span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"related container"</span><span class="nt">&gt;</span>
    Secondary content
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"navigation container"</span><span class="nt">&gt;</span>
    Navigation
<span class="nt">&lt;/div&gt;</span></code></pre></figure>

<p>To make two satellite floats react correctly we need to make sure that our newly added container is also taken out of the normal flow of the document with a float. However, we don’t want surrounding content to flow around it so we should fix its width to 100%.</p>

<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.container</span> <span class="p">{</span>
    <span class="nl">float</span><span class="p">:</span> <span class="nb">left</span><span class="p">;</span>
    <span class="nl">width</span><span class="p">:</span> <span class="m">100%</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<p>Next we want to put some space around our main content using standard margins:</p>

<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.main</span> <span class="p">{</span>
    <span class="nl">margin-left</span><span class="p">:</span> <span class="m">150px</span><span class="p">;</span>
    <span class="nl">margin-right</span><span class="p">:</span> <span class="m">200px</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<p>Now let’s fix the width of those satellite columns:</p>

<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.navigation</span> <span class="p">{</span>
    <span class="nl">width</span><span class="p">:</span> <span class="m">150px</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.related</span> <span class="p">{</span>
    <span class="nl">width</span><span class="p">:</span> <span class="m">200px</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<p>This will result in our three containers floating alongside each other. However, because the first container is set to a width of 100%, the two satellites drop down beneath it.</p>

<p>We want the satellites to take up that nice clear space we’ve created with the normal margins on our main content within the first container. To do that, we shift them left across the first container using negative margins:</p>

<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.navigation</span> <span class="p">{</span>
    <span class="nl">width</span><span class="p">:</span> <span class="m">150px</span><span class="p">;</span>
    <span class="nl">margin-left</span><span class="p">:</span> <span class="m">-100%</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.related</span> <span class="p">{</span>
    <span class="nl">width</span><span class="p">:</span> <span class="m">200px</span><span class="p">;</span>
    <span class="nl">margin-left</span><span class="p">:</span> <span class="m">-200px</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<p>Here we’ve shifted the <code class="highlighter-rouge">navigation</code> container 100% across the width of the <em>container of our floats</em> (in this case, the body of our page). This puts it flush to the left, filling the space to the left of our first floated container.</p>

<p>We then shift the <code class="highlighter-rouge">related</code> container only 200px to the left, matching its width and therefore leaving it flush to the <em>right</em> of the first floated container.</p>

<p>This leaves us with a perfect three-column grid. What’s more, since we’re only fixed the width of our satellites and have left the main content in normal flow, it will respond to the width of its container, as will the position of the satellite floats.</p>

<h2 id="demo-and-source">Demo and source</h2>

<p>I’ve taken the above and scrubbed it up a bit, to create a nice <a href="http://timhuegdon.com/test-cases/flexible-css-grid/">flexible responsive CSS grid demo page</a>. Further to that, I’ve also stuck <a href="http://github.com/nefarioustim/flexible-css-grid">the code up on GitHub in a “flexible CSS grid” repo</a>. Feel free to do with it as you wish.</p>

]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Vagrant Virtualised Dev Environments]]></title>
        <link href="https://nefariousdesigns.co.uk/vagrant-virtualised-dev-environments.html"/>
        <updated>2012-03-14T09:22:00+08:00</updated>
        <id>https://nefariousdesigns.co.uk/vagrant-virtualised-dev-environments</id>
        <content type="html"><![CDATA[<p>In case you’ve been living under a rock for the past couple of years, Vagrant is the latest development in easily controlled virtualised environments. In their own words:</p>

<blockquote>
  <p>The vision of the project is to create a tool to transparently manage all the complex parts of modern development within a virtual environment without affecting the everyday workflow of the developer too much.</p>
</blockquote>

<p>Vagrant automates creation and provisioning of virtual machines within VirtualBox via the command line, whilst also allowing for easy distribution and reuse across multiple projects. In this article, I’m going to look at how it can make life considerably easier when dealing with development environments.</p>

<!--more-->

<h2 id="previously">Previously</h2>

<p>Previously I’ve written a couple of articles on virtualised development environments; <a href="http://nefariousdesigns.co.uk/archive/2009/09/virtualised-development-environments-on-a-mac/">one on VMWare</a> and <a href="http://nefariousdesigns.co.uk/archive/2010/02/mac-virtualbox-linked-clone/">one on VirtualBox</a>. Since then I’ve upgraded my model to use Vagrant, which allows me to control my environment per project, and also fixes me up with painless access to Puppet provisioning.</p>

<p>This has completely altered my workflow for development. To help you to understand why, I’m going to walk through how Vagrant works and then look at setting up a Vagrant-powered development environment.</p>

<h2 id="how-it-works">How it works</h2>

<h3 id="the-base-box">The base box</h3>

<p>The true power of Vagrant lies within its design. The basis of a Vagrant VM is its “base box” which is simply a VirtualBox VM that represents a base install of your system. This base install has the following basic requirements:</p>

<ul>
  <li>VirtualBox Guest Additions for shared folders, port forwarding, etc.</li>
  <li>SSH with key-based auto. support for the vagrant user</li>
  <li>Ruby and RubyGems to install Chef and Puppet</li>
  <li>Chef and Puppet for provisioning support</li>
</ul>

<p>Thankfully the creation of base boxes has been done for you a thousand times over, and the subsequent base box files are available for download at various places across the interwebs. However, should you require something more specific, creating a base box is pretty undemanding and there are even programs like <a href="https://github.com/jedi4ever/veewee/">VeeWee</a> which will automate this process for you.</p>

<p>For more information on building your own base box, take a look at <a href="http://vagrantup.com/docs/base_boxes.html">the Vagrant base box documentation</a>.</p>

<p>If you’d rather download one that someone else has created, take a look here:</p>

<p><a href="http://vagrantbox.es">http://vagrantbox.es</a></p>

<p>This is a really useful resource set-up by <a href="http://morethanseven.net/">Gareth Rushgrove</a>, the man behind <a href="http://devopsweekly.com/">DevOps weekly</a> and also a passionate advocate of Vagrant. If you can’t find the box you need here, create it, host it somewhere, and let Gareth know so he can list it.</p>

<h3 id="the-vagrantfile">The VagrantFile</h3>

<p>Once you’ve got a suitable base box available within Vagrant, you’re ready to start using it as the basis for your development environments. The plural is important here; Vagrant allows you to reuse the base box in generating VMs for multiple projects, each with their own set-up. To best understand that, I’ve drawn a very simple diagram:</p>

<p><img src="/assets/img/vagrantfile.png" alt="One base box can be used by many VagrantFiles, and thus becomes multiple Vagrant boxes." class="central" /></p>

<p>Whilst you’ll probably use the same base box for multiple projects–my box of choice at the moment is a base install Ubuntu 11.10–you probably want a very different set-up per project. For instance, you might have a PHP project that requires a box running Apache and mod_php whilst a Python project better suits nginx proxying to gunicorn. This is entirely possible in Vagrant.</p>

<p>For each project you create, you’ll have a base source directory. It’s here that we’ll create a VagrantFile to control the environment for that project. This means you’ll end up with a VagrantFile per project:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/my_application/
    bin/
    etc/
    lib/
    var/
    VagrantFile
    …

/my_site/
    etc/
    public/
    templates/
    var/
    VagrantFile
    …
</code></pre></div></div>

<p>To create a VagrantFile you simply run the following command in your project directory:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vagrant init
</code></pre></div></div>

<p>This will create a nicely annotated VagrantFile. I recommend reading through it to understand the various settings available for you to configure.</p>

<p>The VagrantFile will allow you to change settings on the VM that vagrant will generate for you; for instance, you might want your VM to only have 512Mb of RAM, whereas another might need 2Gb of RAM. You can also specify what base box to use, what ports are forwarded to the VM, what IP address it is configured with, how the VM should handle networking (bridged, NAT, Host Only etc.), and many other system settings besides.</p>

<h3 id="provisioning">Provisioning</h3>

<p>The VagrantFile also allows you to specify whether you want to provision your VM using Chef or Puppet. In OpsWorld™ [possibly the worst theme-park in the world] this means setting up the software on your VM. Personally, I prefer Puppet for this, simply because it uses an external DSL for configuration which I find easier to read than the internal Ruby DSL that Chef uses. (For an explanation of Domain Specific Languages, see <a href="http://martinfowler.com/bliki/DomainSpecificLanguage.html">Martin Fowler’s excellent blog post, book, and guide page</a>.)</p>

<p>Puppet automates the provisioning, patching, and configuration of operating system and application components across multiple servers. Vagrant uses Puppet to do exactly that; to set-up, patch, and configure the base box to suit your project. To do this, you need to specify that configuration in Puppet manifests–which are basically scripts or programs for Puppet (hence the .pp filename).</p>

<p>The core of the Puppet language is the resource declaration, which represents the desired state of one resource. Manifests can also use conditional statements, group resources into collections, generate text with functions, reference code in other manifests, and do many other things, but it all ultimately comes down to making sure the right resources are being managed the right way.</p>

<p>For more on Puppet and its manifests, I recommend reading the <a href="http://docs.puppetlabs.com/learning/">Learning Puppet documentation</a>. You can probably even skip straight to <a href="http://docs.puppetlabs.com/learning/manifests.html">the manifests section</a>. Also, the resource types cheat sheet is invaluable.</p>

<p>Another useful resource for Puppet is <a href="http://puppetcookbook.com/">the Puppet Cookbook</a>, which contains a collection of task oriented solutions in Puppet.</p>

<p>I’ve recently started keeping a git repository of the various manifests I use for Vagrant. This way, I can copy them and share them between Vagrant projects depending on what software or set-up I require. You can find that repo on GitHub:</p>

<p><a href="http://github.com/nefarioustim/puppet-manifests/">http://github.com/nefarioustim/puppet-manifests/</a></p>

<p>Be aware, I tend to use Ubuntu server hence package management is handled via <code class="highlighter-rouge">apt</code>. This means these manifests will need a bit of editing should you want to use them on CentOS or some other linux distro.</p>

<h3 id="the-vagrant-vm">The Vagrant VM</h3>

<p>The Vagrant VM will be created according to your VagrantFile. This means there will be one per project. This granularity affords you a degree of independence with the VM, and allows you to treat it as a really powerful isolated root for your project. If you’ve ever used <code class="highlighter-rouge">virtualenv</code> when working with Python, imagine Vagrant to be <code class="highlighter-rouge">virtualenv</code> squared. Since you’re not sharing this environment with any other project, you can set it up, alter it, reconfigure it, and destroy it as much as you please; and since it’s entirely controlled by the VagrantFile and the provisioning scripts, those processes are easy <em>and</em> powerful.</p>

<p>Once set-up, your vagrant VM contains a default user of <code class="highlighter-rouge">vagrant</code>. That user has full sudo access and is generally the user you’ll use for everything within your development environment. When you think about it, there’s no real need for complex user set-up within this VM since you could be setting it up and tearing it down as much as you’re doing development on it. If you <em>do</em> need complex user set-ups, there’s nothing stopping you doing that with Puppet or Chef during the provisioning stage.</p>

<p>The Vagrant VM itself can be controlled at the command line through a number of commands:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vagrant up
</code></pre></div></div>

<p>The first time you run this command, it will copy across the base box specified in your VagrantFile, boot it up with the specified networking set-up, and then provision it according to your Puppet manifests or Chef recipes. Once the box has been set up, and as long as it isn’t destroy, this command will boot up the box and confirm the provisioning. You can deactivate provisioning on this command using the <code class="highlighter-rouge">--no-provision</code> switch.</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vagrant ssh
</code></pre></div></div>

<p>Logs into your project VM as the <code class="highlighter-rouge">vagrant</code> user, using SSH keys. This circumvents the need for complicated SSH set-ups on your host machine and affords you all the power you need.</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vagrant destroy
</code></pre></div></div>

<p>This will remove all trace of your project VM from within VirtualBox. This means, the next time you run <code class="highlighter-rouge">vagrant up</code>, Vagrant will need to recopy across the base box and reprovision it. Most of the time you’ll only really want to do this if you’ve b0rked your VM somehow, or you’ve made a significant change to your VagrantFile; like specifying a different base box for example.</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vagrant suspend
</code></pre></div></div>

<p>Takes a snapshot of your VM and suspends it, allowing you to <code class="highlighter-rouge">vagrant resume</code> later. This saves you having to perform a length <code class="highlighter-rouge">vagrant destroy &amp;&amp; vagrant up</code> cycle, but also stops the VM from taking up valuable memory and CPU cycles.</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vagrant resume
</code></pre></div></div>

<p>Resumes a suspended VM from its snapshot state. The <code class="highlighter-rouge">vagrant up</code> command will also resume if it detects a suspended VM.</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vagrant halt
</code></pre></div></div>

<p>Forces shutdown of a VM. This is basically a last resort shut down of your VM and the folks over at Vagrant recommend attempting a graceful shutdown via <code class="highlighter-rouge">vagrant ssh</code> first.</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vagrant status
</code></pre></div></div>

<p>Shows the current status of the VM related to the VagrantFile in the current directory.</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vagrant provision
</code></pre></div></div>

<p>Runs the provisioning scripts without reloading the entire Vagrant environment. If you’re just tweaking or adding some cookbooks, this command can save you a lot of time.</p>

<p>There are a few other Vagrant commands available to you but the above are pretty much the majority of what you’ll use on a daily basis. For the complete list, see <a href="http://vagrantup.com/docs/commands.html">the Vagrant commands documentation</a>.</p>

<h2 id="an-example-vagrant-environment">An example Vagrant environment</h2>

<p>Now that I’ve run through the workings hopefully you’ve got a better understanding of the power of Vagrant and how it can improve your development workflow. To further highlight that, let’s set-up a basic example Vagrant environment on a Mac, via the command line.</p>

<h3 id="installation-the-best-way">Installation the best way</h3>

<p>With the release of v1.0 of Vagrant comes a new set of <a href="http://downloads.vagrantup.com/">installation packages, available from the Vagrant downloads section</a>. This is by far the best way to install Vagrant and will sort you out with all the prerequisites automatically. These are now the recommended and supported method of installation for Vagrant.</p>

<p>When I began writing this article, these packages did not exist and, as such, I covered the slightly more complicated installation with all its prerequisites (for Mac). With these new packages, you should be able to follow along with the majority of this tutorial in Windows (albeit with slightly differing CLI commands).</p>

<h3 id="installation-the-old-way">Installation the old way</h3>

<h4 id="apple-developer-tools">Apple Developer Tools</h4>

<p>You’ll need to either install Xcode or the newly created Command Line Tools (significantly smaller than the full Xcode install and designed for stuff like this), which you can download from Apple (you’ll need a free Apple ID to log in):</p>

<p><a href="https://developer.apple.com/downloads/">https://developer.apple.com/downloads/</a></p>

<h4 id="homebrew">Homebrew</h4>

<p>Firstly, I’d recommend you install some package management for which I use <a href="http://mxcl.github.com/homebrew/">Homebrew</a>. Whilst this is not required—you can always install from source—it <em>is</em> lightyears ahead of MacPorts (the alternative package manager for Mac) and is <a href="https://github.com/mxcl/homebrew/">actively supported on GitHub</a>. If you don’t have it already, do this:</p>

<pre><samp>$</samp> <kbd>/usr/bin/ruby -e "$(curl -fsSL https://raw.github.com/gist/323731)"</kbd></pre>

<p>This is the <a href="https://github.com/mxcl/homebrew/wiki/installation">recommended install for Homebrew</a>. If you’re unsure, <a href="https://gist.github.com/323731">read the script first</a>. It installs Homebrew to <code class="highlighter-rouge">/usr/local</code> so that you don’t need sudo when you <code class="highlighter-rouge">brew install</code>. It is a careful script, it can be run even if you have stuff installed to <code class="highlighter-rouge">/usr/local</code> already. It tells you exactly what it will do before it does it too. And you have to confirm everything it will do before it starts.</p>

<p>You can then use Homebrew to update your Ruby and RubyGems installs</p>

<h4 id="ruby-and-rubygems">Ruby and RubyGems</h4>

<p>Vagrant is powered by Ruby and is installed as a RubyGem. This means you require both Ruby and RubyGems on your development VM host machine. Both are preinstalled on Mac OS, so we only need to update them:</p>

<pre><samp>$</samp> <kbd>sudo gem update --system</kbd></pre>

<h4 id="install-the-gem">Install the gem</h4>

<p>Once you’ve made sure you’ve installed all the requirements for Vagrant, the actual installation is really simple. Just install the Vagrant RubyGem:</p>

<pre><samp>$</samp> <kbd>gem install vagrant</kbd></pre>

<p>Installing this gem will also install VirtualBox (if you haven’t already).</p>

<p>Bob’s your uncle, Mary’s your aunt, and Dave’s your vicar’s love-slave. You are now ready to start building Vagrant environments, but first you’ll need at least one base box.</p>

<h3 id="base-box">Base box</h3>

<p>You now have the option of downloading a base box, or you can build your own in VirtualBox using your operating system of choice. Since this is supposed to be a development environment, I’d recommend choosing an OS that is as close as possible to the one you’re going to use in production. For me that tends to be Debian or Ubuntu (which is really just another flavour of Debian), so I’m working with an Ubuntu base box.</p>

<h4 id="building-your-own-base-box">Building your own base box</h4>

<p>Creating a base box is straightforward as long as you’re confident building and provisioning servers. If you’re a bit unsure but you’re not scared to give it a go, I heartily recommend trying to build your own because it’s certainly a learning experience.</p>

<p>To begin with, get yourself a disk image of your chosen OS. For me, that’s Ubuntu 11.10 Server AMD64. Once you’ve got your image, you’re ready to start setting up a VM in VirtualBox.</p>

<p>My template for new VMs is:</p>

<ul>
  <li>360Mb RAM</li>
  <li>10GB VDI disk, dynamically sized</li>
  <li>64 bit
    <ul>
      <li>In General &gt; Basic choose Linux &gt; Ubuntu (64 bit) as your OS</li>
      <li>Set System &gt; Motherboard &gt; Enable IO APIC to true</li>
      <li>Set System &gt; Processor &gt; Enable PAE/NX to true</li>
    </ul>
  </li>
  <li>Disable audio</li>
  <li>Disable floppy drive</li>
</ul>

<p>Once that’s set-up, make sure you’ve “inserted” your OS disk image to the CD/DVD drive on the VM, and fire it up. I generally opt for a standard install for my base box, but if your OS of choice offers a low footprint install intended for virtualisation, you may want to opt to use that instead. If you do, make sure you know the differences; it may use a different kernel and therefore not support some of the motherboard and processor settings we discussed earlier.</p>

<p>When the time comes, make sure you use a default user of:</p>

<ul>
  <li>Fullname: vagrant</li>
  <li>Username: vagrant</li>
  <li>Password: vagrant</li>
</ul>

<h5 id="post-install">Post install</h5>

<p><a href="https://gist.github.com/db79878aa0e7eae56caa">I’ve written a script to handle post install</a> in a similar method to VeeWee. To use this you’ll need to create a <code class="highlighter-rouge">.vbox_version</code> file in your home dir:</p>

<pre><samp>$</samp> <kbd>echo "4.1.8" &gt; ~/.vbox_version</kbd></pre>

<p>You’ll want to replace the “4.1.8” with the relevant version of your VirtualBox installation because this will be used to work out which Guest Additions to install. Next let’s switch to root for ease:</p>

<pre><samp>$</samp> <kbd>sudo -i</kbd></pre>

<p>You’ll also want to make sure cUrl is installed:</p>

<pre><samp>$</samp> <kbd>apt-get install -y curl</kbd></pre>

<p>Once you’ve done that, we can download and run the script (<a href="http://git.io/cSGCgw">raw gist URL shortened for convenience here</a>):</p>

<pre><samp>$</samp> <kbd>curl -L http://git.io/cSGCgw | bash</kbd></pre>

<p>If you read through the script you’ll see it does the following:</p>

<ol>
  <li>Creates a log of the date and time we built the box in <code class="highlighter-rouge">/etc</code></li>
  <li>Installs <code class="highlighter-rouge">aptitude</code></li>
  <li>Updates the package list</li>
  <li>Upgrades the installed packages</li>
  <li>Installs a bunch of packages that are useful for set-up</li>
  <li>Installs SSH</li>
  <li>Installs the NFS client</li>
  <li>Sets-up the correct permissions in <code class="highlighter-rouge">sudoers</code></li>
  <li>Installs Ruby and RubyGems</li>
  <li>Installs the Chef and Puppet gems and updates the JSON gem</li>
  <li>Removes the the gemspec for an older version of JSON because it’s broken</li>
  <li>Installs the insecure Vagrant public keys supplied by Mitchell Hashimoto</li>
  <li>Makes sure SSH doesn’t use DNS look-ups</li>
  <li>Installs the VirtualBox Guest Additions</li>
  <li>Zeros out the free space in the image to make it easier to compress</li>
  <li>Removes leftover DHCP and network rules</li>
</ol>

<p>Once the script completes you should be ready to rock. Better shut down that VM:</p>

<pre><samp>$</samp> <kbd>sudo shutdown -P now</kbd></pre>

<h4 id="package-up-your-self-built-base-box">Package up your self-built base box</h4>

<p>Assuming the VM you created in VirtualBox is called “ubuntu-11.10”, we package it up using the following command:</p>

<pre><samp>$</samp> <kbd>vagrant package --base ubuntu-11.10 --out ubuntu-11.10.box</kbd></pre>

<p>The <code class="highlighter-rouge">--base</code> parameter refers to the VM in VirtualBox and the <code class="highlighter-rouge">--out</code> parameter is what we want our newly packaged <code class="highlighter-rouge">.box</code> file to be called. Once you have a <code class="highlighter-rouge">.box</code> file, you’re ready to start using it with Vagrant–and you’re also ready to share it with other people should you so wish.</p>

<h4 id="using-a-pre-built-base-box">Using a pre-built base box</h4>

<p>In true <a href="http://en.wikipedia.org/wiki/Blue_Peter">Blue Peter</a> fashion, here’s one I made earlier:</p>

<p><a href="http://timhuegdon.com/vagrant-boxes/ubuntu-11.10.box">http://timhuegdon.com/vagrant-boxes/ubuntu-11.10.box</a></p>

<p>For other options, as previously mentioned, have a look at <a href="http://vagrantbox.es">Vagrantbox.es</a>.</p>

<h3 id="making-vagrant-aware-of-your-base-box">Making Vagrant aware of your base box</h3>

<p>Assuming you’re in the same directory as your <code class="highlighter-rouge">.box</code> file, you can add it to Vagrant using the following command:</p>

<pre><samp>$</samp> <kbd>vagrant box add ubuntu-11.10 ubuntu-11.10.box</kbd></pre>

<p>The first parameter is the name Vagrant will use to refer to the box in Vagrantfiles, and the last is the path to your <code class="highlighter-rouge">.box</code> file.</p>

<h3 id="configuring-your-vagrantfile">Configuring your VagrantFile</h3>

<p>Now that you’ve downloaded or created a base box, and have made Vagrant aware of it, our next step is to configure a VagrantFile for whatever project we’re working on. It’s here, amongst other things, that we’ll specify which base box we want to use.</p>

<p>Change directory to your project and run <code class="highlighter-rouge">vagrant init</code>:</p>

<pre><samp>$</samp> <kbd>cd ~/projects/myproject</kbd>
<samp>$</samp> <kbd>vagrant init</kbd></pre>

<p>Vagrant will have now created a VagrantFile at the root of that directory. Let’s open that in the editor of your choice–which for me is Sublime Text 2:</p>

<pre><samp>$</samp> <kbd>subl VagrantFile</kbd></pre>

<p>If you’ve ever worked with Chef before, or indeed Ruby, you’ll recognise that the VagrantFile is Ruby. You’ll also notice that the folks at Vagrant have made newly created VagrantFiles wonderfully verbose, and if you read through the annotations, all the settings are explained.</p>

<p>For our Vagrant VM we’re going to want to use our base box, so update that line in the Vagrant file to:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>config.vm.box = "ubuntu-11.10"
</code></pre></div></div>

<p>Since we’ve already installed this base box, we don’t need the VagrantFile to be aware of a hosting URL, so leave that line commented.</p>

<p>The next line defines whether you want to run your VM headless (i.e. without firing up the VirtualBox GUI). Generally the only time you’ll want to uncomment this line is if you’re debugging a problem with the VM. Most of the time you won’t want to waste system resources on the VirtualBox GUI. With that in mind, leave it commented.</p>

<p>Now we can choose networking options. For the purposes of this example I’m assuming we’re working on a local development machine and, as such, host-only networking will suit our purposes. If we were working on a separate dev box that may host multiple VMs, we’d probably want to use bridged networking to expose them to the network. For now though, just uncomment the following line:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>config.vm.network :hostonly, "33.33.33.10"
</code></pre></div></div>

<p>This means the VM will be exposed to the host machine on the IP address 33.33.33.10, and will be able to access your network. However, machines other than your host machine <em>will not</em> be able to see the VM.</p>

<p>Since we’ve uncommented this line, leave the bridged networking line commented.</p>

<p>Now we have the opportunity to forward some ports from the host to the guest OS. This can be useful if you want to temporarily expose a host-only network VM to machines on your network, however, for the purposes of this tutorial, please leave this line commented too. Later on we’re going to install a web server and connect to this VM as if it were any other server on our network, so port forwarding is not required here.</p>

<p>Next we need to define some folders to share with the VM, and how to share them. It’s a well recorded fact that when using VirtualBox on a unix-based system it struggles as the number of files within any shared folder increases. For this reason, if you’re running Vagrant on a Mac, it’s better to use NFS to mount your directories—Windows does not suffer the same issue so NFS is not required.</p>

<p>To set up a directory to share on your Vagrant VM, simply declare it as follows:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>config.vm.share_folder("v-root", "/vagrant", ".", :nfs =&gt; true)
</code></pre></div></div>

<p>This will create a directory <code class="highlighter-rouge">/vagrant</code> at the root of your VM. That folder will be shared with the directory on the host containing your Vagrantfile, implied by the <code class="highlighter-rouge">.</code> directory reference. For a Windows host, just set <code class="highlighter-rouge">nfs: =&gt; false</code>.</p>

<p>Now we can choose how the Vagrant VM is provisioned. As I said earlier, I personally prefer to use Puppet, so uncomment the following lines and update the manifests path. I find “puppet” is more obvious than “manifests”:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>config.vm.provision :puppet do |puppet|
  puppet.manifests_path = "puppet"
  puppet.manifest_file  = "base.pp"
end
</code></pre></div></div>

<p>This will look for our base manifest, “base.pp”, in a directory called “puppet” at the same directory level as our VagrantFile. We’ll set that up later.</p>

<p>Finally, let’s add a last line to our VagrantFile to tell it to set-up a VM with 512Mb of memory:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>config.vm.customize ["modifyvm", :id, "--memory", "512"]
</code></pre></div></div>

<p>You’ll notice this particular command isn’t annotated in the VagrantFile. For more information about customising the specific characteristics of the VM, take a look at the Vagrant docs.</p>

<p>Once you’ve completed these changes, your VagrantFile should look something like this (if you remove all the commented lines):</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># -*- mode: ruby -*-</span>
<span class="c1"># vi: set ft=ruby :</span>

<span class="no">Vagrant</span><span class="o">::</span><span class="no">Config</span><span class="p">.</span><span class="nf">run</span> <span class="k">do</span> <span class="o">|</span><span class="n">config</span><span class="o">|</span>
    <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">box</span> <span class="o">=</span> <span class="s2">"ubuntu-11.10"</span>

    <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">network</span> <span class="ss">:hostonly</span><span class="p">,</span> <span class="s2">"33.33.33.10"</span>

    <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">share_folder</span><span class="p">(</span><span class="s2">"v-root"</span><span class="p">,</span> <span class="s2">"/vagrant"</span><span class="p">,</span> <span class="s2">"."</span><span class="p">,</span> <span class="ss">:nfs</span> <span class="o">=&gt;</span> <span class="kp">true</span><span class="p">)</span>

    <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:puppet</span> <span class="k">do</span> <span class="o">|</span><span class="n">puppet</span><span class="o">|</span>
        <span class="n">puppet</span><span class="p">.</span><span class="nf">manifests_path</span> <span class="o">=</span> <span class="s2">"puppet"</span>
        <span class="n">puppet</span><span class="p">.</span><span class="nf">manifest_file</span>  <span class="o">=</span> <span class="s2">"base.pp"</span>
    <span class="k">end</span>

    <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">customize</span> <span class="p">[</span><span class="s2">"modifyvm"</span><span class="p">,</span> <span class="ss">:id</span><span class="p">,</span> <span class="s2">"--memory"</span><span class="p">,</span> <span class="s2">"512"</span><span class="p">]</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Our Vagrantfile will now create exactly the VM we require when we run the <code class="highlighter-rouge">vagrant up</code> command. However, the VM itself only contains the software installed as part of the base box. Since this VM is serving our project, we probably want some more stuff on there like a web server or a particular version of a language. To set that up, we’ll need to use a <em>provisioner</em> which is where Puppet comes in. (If you want to use Chef, don’t let me stop you. I just won’t be covering Chef here.)</p>

<h3 id="provisioning-with-puppet">Provisioning with Puppet</h3>

<p>Provisioning happens in Vagrant every time we run <code class="highlighter-rouge">vagrant up</code> or <code class="highlighter-rouge">vagrant provision</code>. This sets up the software on your VM according to a set of manifests (or “recipes” in Chef). Those manifests basically tell Puppet what it should script on the VM. This means you can update <em>anything</em>, including copying across files, updating files already on the system, installing and uninstalling packages, changing permissions, stopping and starting services, and a whole host of other software changes.</p>

<p>To do this, you’ll need to learn Puppet’s manifest language. This is a custom DSL that is quite easy to learn; although the Puppet documentation can be a little difficult to navigate. I’d recommend looking at:</p>

<ul>
  <li><a href="http://docs.puppetlabs.com/learning/">Learning Puppet</a></li>
  <li><a href="http://docs.puppetlabs.com/#reference-shelf">Puppet Docs Reference Shelf</a></li>
  <li><a href="http://docs.puppetlabs.com/#basic-features-and-use">Basic Features and Use</a></li>
  <li><a href="http://docs.puppetlabs.com/puppet_core_types_cheatsheet.pdf">Core Types Cheat Sheet PDF</a></li>
</ul>

<p>To begin, let’s set up a directory in our project folder to contain our manifests, and another folder within that to contain any files we may want to copy across to our guest OS with Puppet. From the directory on your host that contains your Vagrantfile do:</p>

<pre><samp>$</samp> <kbd>mkdir -p ./puppet/files</kbd></pre>

<p>Now in the newly created <code class="highlighter-rouge">puppet</code> folder, create a file entitled <code class="highlighter-rouge">base.pp</code>:</p>

<pre><samp>$</samp> <kbd>cd puppet &amp;&amp; touch base.pp</kbd></pre>

<p>Note that Puppet manifests have the <code class="highlighter-rouge">.pp</code> extension. You should be able to find syntax rules for all good editors to deal with this extension and file type.</p>

<p>Open up the newly created <code class="highlighter-rouge">base.pp</code> file in your editor of choice. Puppet manifests have a number of constructs, chief of which is the concept of a “resource”. Resources can be packages, files, executed commands, users, groups and services. These resources can then be organised within classes. So let’s start with a class for our dev box:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>class devbox {
}
</code></pre></div></div>

<p>As an example, let’s set-up nginx as a web server. To do that, the first thing we’re going to need to do is install the package:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">package</span> <span class="p">{</span> <span class="s2">"nginx"</span><span class="p">:</span>
    <span class="n">ensure</span> <span class="p">=&gt;</span> <span class="n">latest</span>
<span class="p">}</span>
</code></pre></div></div>

<p>That was quite simple, right? Puppet already knows to use <code class="highlighter-rouge">apt</code> as the default package installer on Ubuntu, so this command checks the apt-cache to see if the latest version of the package is installed, and if it isn’t installs it.</p>

<p>Now we should make sure the nginx service is running:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>service { "nginx":
    ensure =&gt; running,
    hasrestart =&gt; true
}
</code></pre></div></div>

<p>Equally simple. Here we’ve told Puppet to check the service nginx is running, and we’ve also informed it that the service has a restart function which Puppet can make use of.</p>

<p>I’ve stuck a bunch of <a href="http://github.com/nefarioustim/puppet-manifests/">hacked together Puppet manifests into a repository on GitHub</a>. Feel free to poke about in them; I’ll be updating them as I do more stuff with Vagrant. For now, at least, take a look at the <a href="https://github.com/nefarioustim/puppet-manifests/tree/master/files">files directory</a> because we can repurpose some of my set-up for this example. Save the following from my repo to your <code class="highlighter-rouge">puppet/files</code> directory which we created earlier:</p>

<ul>
  <li><code class="highlighter-rouge">files/nginx.conf</code></li>
  <li><code class="highlighter-rouge">files/vhost.conf</code></li>
</ul>

<p>Now we need to get these files from your host computer to the guest OS in the Vagrant VM. Once again, this is pretty simple:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>file { "/etc/nginx/nginx.conf":
    owner  =&gt; root,
    group  =&gt; root,
    mode   =&gt; 644,
    source =&gt; "puppet:////vagrant/puppet/files/nginx.conf"
}

file { "/etc/nginx/sites-available/vagrantsite":
    owner  =&gt; root,
    group  =&gt; root,
    mode   =&gt; 644,
    source =&gt; "puppet:////vagrant/puppet/files/vhost.conf"
}
</code></pre></div></div>

<p>Notice the source exists within our <code class="highlighter-rouge">/vagrant</code> directory, which we’ve already set-up as a NFS shared directory. This means we’re effectively copying the file from there to the <code class="highlighter-rouge">/etc/nginx/</code> directory on the guest. Also, if the destination directory does not already exist, Puppet will create it. Notice how I’m also setting the owner, group, and mode of the file during the copy.</p>

<p>So far we’re getting along fine, but wouldn’t it be nice if we could let Puppet know we’d like to handle these stages in some semblance of an order? We can do that in the resources using the <code class="highlighter-rouge">require</code> parameter:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>file { "/etc/nginx/nginx.conf":
    owner  =&gt; root,
    group  =&gt; root,
    mode   =&gt; 644,
    source =&gt; "puppet:////vagrant/puppet/files/nginx.conf",
    require =&gt; Package["nginx"]
}
</code></pre></div></div>

<p>Note the reference to the resource we require is capitalised? This is a subtle difference between declaring and reference a resource.</p>

<p>What would also be nice is if we could tell the nginx service that, by changing the configuration files, we’d like it to restart. To do that we use the <code class="highlighter-rouge">notify</code> param:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>file { "/etc/nginx/nginx.conf":
    owner  =&gt; root,
    group  =&gt; root,
    mode   =&gt; 644,
    source =&gt; "puppet:////vagrant/puppet/files/nginx.conf",
    require =&gt; Package["nginx"],
    notify =&gt; Service["nginx"]
}
</code></pre></div></div>

<p>We just have a couple more things to do now. Firstly, let’s create a symbolic link to <code class="highlighter-rouge">sites-available</code> from within <code class="highlighter-rouge">sites-enabled</code> so that our newly copied across vhost is picked up by the nginx configuration:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>file { "/etc/nginx/sites-enabled/vagrantsite":
    ensure =&gt; symlink,
    target =&gt; "/etc/nginx/sites-available/vagrantsite",
    require =&gt; Package["nginx"],
    notify =&gt; Service["nginx"]
}
</code></pre></div></div>

<p>Notice I haven’t required the original file for this. That’s because it’s not a requirement for creating the symlink in the first place.</p>

<p>Secondly, let’s remove the default vhost because we don’t need it:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>file { "/etc/nginx/sites-enabled/default":
    ensure =&gt; absent,
    require =&gt; Package["nginx"],
    notify =&gt; Service["nginx"]
}
</code></pre></div></div>

<p>With all that in place, and adding a full set of <code class="highlighter-rouge">require</code> and <code class="highlighter-rouge">notify</code> parameters, our final class should look like this:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">class</span> <span class="n">devbox</span> <span class="p">{</span>
    <span class="k">package</span> <span class="p">{</span> <span class="s2">"nginx"</span><span class="p">:</span>
        <span class="n">ensure</span> <span class="p">=&gt;</span> <span class="n">latest</span><span class="p">,</span>
    <span class="p">}</span>

    <span class="n">file</span> <span class="p">{</span> <span class="s2">"/etc/nginx/nginx.conf"</span><span class="p">:</span>
        <span class="n">owner</span>  <span class="p">=&gt;</span> <span class="n">root</span><span class="p">,</span>
        <span class="n">group</span>  <span class="p">=&gt;</span> <span class="n">root</span><span class="p">,</span>
        <span class="n">mode</span>   <span class="p">=&gt;</span> <span class="m">644</span><span class="p">,</span>
        <span class="n">source</span> <span class="p">=&gt;</span> <span class="s2">"puppet:////vagrant/puppet/files/nginx.conf"</span><span class="p">,</span>
        <span class="n">require</span> <span class="p">=&gt;</span> <span class="k">Package</span><span class="p">[</span><span class="s2">"nginx"</span><span class="p">],</span>
        <span class="n">notify</span> <span class="p">=&gt;</span> <span class="n">Service</span><span class="p">[</span><span class="s2">"nginx"</span><span class="p">]</span>
    <span class="p">}</span>

    <span class="n">file</span> <span class="p">{</span> <span class="s2">"/etc/nginx/sites-available/vagrantsite"</span><span class="p">:</span>
        <span class="n">owner</span>  <span class="p">=&gt;</span> <span class="n">root</span><span class="p">,</span>
        <span class="n">group</span>  <span class="p">=&gt;</span> <span class="n">root</span><span class="p">,</span>
        <span class="n">mode</span>   <span class="p">=&gt;</span> <span class="m">644</span><span class="p">,</span>
        <span class="n">source</span> <span class="p">=&gt;</span> <span class="s2">"puppet:////vagrant/puppet/files/vhost.conf"</span><span class="p">,</span>
        <span class="n">require</span> <span class="p">=&gt;</span> <span class="k">Package</span><span class="p">[</span><span class="s2">"nginx"</span><span class="p">],</span>
        <span class="n">notify</span> <span class="p">=&gt;</span> <span class="n">Service</span><span class="p">[</span><span class="s2">"nginx"</span><span class="p">]</span>
    <span class="p">}</span>

    <span class="n">file</span> <span class="p">{</span> <span class="s2">"/etc/nginx/sites-enabled/vagrantsite"</span><span class="p">:</span>
        <span class="n">ensure</span> <span class="p">=&gt;</span> <span class="n">symlink</span><span class="p">,</span>
        <span class="n">target</span> <span class="p">=&gt;</span> <span class="s2">"/etc/nginx/sites-available/vagrantsite"</span><span class="p">,</span>
        <span class="n">require</span> <span class="p">=&gt;</span> <span class="k">Package</span><span class="p">[</span><span class="s2">"nginx"</span><span class="p">],</span>
        <span class="n">notify</span> <span class="p">=&gt;</span> <span class="n">Service</span><span class="p">[</span><span class="s2">"nginx"</span><span class="p">]</span>
    <span class="p">}</span>

    <span class="n">file</span> <span class="p">{</span> <span class="s2">"/etc/nginx/sites-enabled/default"</span><span class="p">:</span>
        <span class="n">ensure</span> <span class="p">=&gt;</span> <span class="n">absent</span><span class="p">,</span>
        <span class="n">require</span> <span class="p">=&gt;</span> <span class="k">Package</span><span class="p">[</span><span class="s2">"nginx"</span><span class="p">],</span>
        <span class="n">notify</span> <span class="p">=&gt;</span> <span class="n">Service</span><span class="p">[</span><span class="s2">"nginx"</span><span class="p">]</span>
    <span class="p">}</span>

    <span class="n">service</span> <span class="p">{</span> <span class="s2">"nginx"</span><span class="p">:</span>
        <span class="n">ensure</span> <span class="p">=&gt;</span> <span class="n">running</span><span class="p">,</span>
        <span class="n">hasrestart</span> <span class="p">=&gt;</span> <span class="nb">true</span><span class="p">,</span>
        <span class="n">require</span> <span class="p">=&gt;</span> <span class="k">Package</span><span class="p">[</span><span class="s2">"nginx"</span><span class="p">]</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The next time we fire up our Vagrant VM, nginx will be installed, set-up, and running, and attempting to serve a website from the <code class="highlighter-rouge">/vagrant/static</code> directory on your guest OS. This will be the <code class="highlighter-rouge">static</code> directory within the same directory as your Vagrantfile on the host.</p>

<p>On the host, let’s create that directory and stick a very basic file in it:</p>

<pre><samp>$</samp> <kbd>mkdir static &amp;&amp; cd $_</kbd>
<samp>$</samp> <kbd>echo 'Hello world from my Vagrant VM!'' &gt; index.html</kbd></pre>

<p>Not the most well-formed example, but it’ll do. Now let’s fire up the Vagrant VM:</p>

<pre><samp>$</samp> <kbd>vagrant up</kbd></pre>

<p>This should copy across the base box we installed, set-up all the things we specified in the Vagrantfile, and begin provisioning from our manifest. You should see messaged that Puppet has successfully installed nginx and the relevant files, and that the service is running. Now point your browser to:</p>

<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>33.33.33.10
</code></pre></div></div>

<p>Ta da! You have successfully set-up a vagrant development environment with specific software requirements for a specific project. Congratulations! Now go away and hack it.</p>

<h2 id="summary">Summary</h2>

<p>So this has been an epic 5000 word look at why Vagrant is now my development environment tool of choice. I hope you can see that it makes working with multiple projects—each with their own requirements for an environment—as simple as possible. With a good understanding of the features of Vagrant, and also of the provisioning tool of your choice, you really do have the power to fire up and destroy environments on a whim.</p>

<p>Apologies for the sheer size of this article but I wanted to make sure I covered as much as possible to help newbies get up and running quickly. It doesn’t take much effort, and it really empowers developers to be able to spin up new environments quickly for hacking around in.</p>

]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Spring reboot]]></title>
        <link href="https://nefariousdesigns.co.uk/spring-reboot.html"/>
        <updated>2012-03-05T01:46:32+08:00</updated>
        <id>https://nefariousdesigns.co.uk/spring-reboot</id>
        <content type="html"><![CDATA[<p>If you’re looking at the site and not the feed you’ve probably noticed some significant changes. After 5 long years of a heavily doctored Wordpress implementation with custom templates I’ve finally gotten around to rebooting the site, bringing it more in line with my requirements.</p>

<p>It’s more of a realignment rather than a redesign. I’ve trimmed back the cruft, and improved what I believe is important—and I’ve also made some more drastic changes which can be reversed should I want to.</p>

<p>So, without further ado, let me just take some time to explain my reasons…</p>

<!--more-->

<h2 id="technology">Technology</h2>

<p>The site is now statically generated by <a href="http://jekyllrb.com/">Jekyll</a> in Ruby instead of dynamically on request via <a href="http://wordpress.org/">Wordpress</a> in PHP. This has allowed me to rebuild my server and ditch a bunch of technologies I no longer work with. Key amongst those are MySQL and PHP, but I also no longer need Apache. It’s also made the site faster and less in need of a caching solution.</p>

<p>Statically generating the site has also meant I’ve ditched some more dynamic functionality like the contact form and—more importantly—comments. Considering the ratio of signal to noise in the comments posted to my site, and the sheer weight of spam, I’m reasonably confident I won’t miss them. What’s more, with the constant discussion on Twitter and the fact that I can easily bring comments back later with Disqus, I have the option for resurrection should I desire it.</p>

<p>Jekyll has some pretty cool extensions and plug-ins, and if you take a look at some of my more code filled posts you’ll notice the code samples are now styled up with the help of <a href="http://pygments.org/">Pygments</a>, a python library that marks-up the code for styling in CSS. It’s the same system used by <a href="http://github.com">GitHub</a>.</p>

<p>I’ve used an HTML5 doctype so I can add modern features as they become more widely supported cross-browser. I’ve also used a fair amount of CSS3 so I hope you’re browsing using an up to date browser rather than something as flawed as Internet Explorer.</p>

<p>The styling now requires nothing but CSS and web fonts. I have significantly reduced the number of images required to make the site look pretty. This means the number of HTTP requests made by the page is significantly smaller and overall the site performs better in YSlow and PageSpeed. I have to say, this wasn’t a primary concern but it’s nice to get it without trying too hard.</p>

<p>My new site is now much easier to deploy and update and I’ve made use of all the good stuff I’ve learnt about server administration over the past few years. You could say it’s all much more DevOps-like in approach and makes use of stuff like Puppet, Rake, and SASS.</p>

<h2 id="design">Design</h2>

<p>I wanted to make sure I was designing for my content and not trying to fill space with extra information that nobody really wanted. Hence, the right hand menu has been replaced by much wider blog posts. Hopefully that’ll do away with a few of the nasty horizontal scrollbars that crept into some of my code examples whilst also giving the main content of the site room to breathe.</p>

<p>The typography of the site should now be significantly more predictable cross-browser. I’ve used <code class="highlighter-rouge">@font-face</code> before but it’s nice to use it for one’s own devices. Hopefully this new iteration is much easier to read than the last, and makes better use of the space available.</p>

<p>I’ve improved everything for SEO; flattening the site architecture, making sure to include descriptions, moving navigation below the main content, and defining canonical URIs. I’ve also got plans for the category pages but need some more time to plan out the work and felt it wasn’t really a blocker for launch.</p>

<h2 id="the-future">The future</h2>

<p>So apart from the SEO stuff I’d still like to work in, I’ve still got some work to do on the responsiveness of the site. Currently it’s not looking great for screens less than 480px in width and I need to rethink some positional stuff to make it work.</p>

<p>For the moment I’m reasonably happy with the site, and with some more work on it over the coming months I’m sure I can turn it into something I’m much more comfortable with. The real target was to make the core content more readable and I think I’ve achieved that. I only hope you, as a reader, agree.</p>

]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[User-controlled content density]]></title>
        <link href="https://nefariousdesigns.co.uk/user-controlled-content-density.html"/>
        <updated>2012-01-07T06:37:07+08:00</updated>
        <id>https://nefariousdesigns.co.uk/user-controlled-content-density</id>
        <content type="html"><![CDATA[<p>Back in October of last year <a href="http://googledocs.blogspot.com/2011/10/experience-new-look-of-docs-and-sites.html">Google Apps underwent a fairly extensive redesign</a>. The overall intent of this realignment was to improve the user interface design, which has traditionally seemed to be a stumbling point for Google.</p>

<p>Personally I think the new designs are excellent and really appreciate the fact that they address my need to access my Google Apps from a variety of devices. I also like the fact that they allow me my own preference for the visual density of content within the page.</p>

<p>In fact this is such a killer feature that I reverse engineered it to better understand it. I’ll be looking to use this knowledge in some of my future work. Whilst I wouldn’t really refer to this deconstruction as such, plagiarism is the sincerest form of flattery. Unfortunately, due to extensive work commitments, I’ve only just gotten around to writing up my work…</p>

<!--more-->

<h2 id="responsive">Responsive</h2>

<p>It’s my opinion that this technique relates quite closely to the responsive design ethos. The visual content density should respond to both the user’s available screen real-estate, their chosen font-size, and their own preference—which should always override any other external actors.</p>

<p>The majority of responsive design discussions and tutorials seem to talk extensively around how a design responds only to the client width. True responsiveness, however, equates to so much more than this.</p>

<h2 id="visual_density">Visual density</h2>

<p>In this article I am referring to <em>visual</em> content density. This refers to the actual physical space around the content and is not to be confused with keyword density, which is concerned with the proliferation of words and phrases <em>within</em> said content. Balanced visual content density is an important factor towards improved typography, improved legibility, and an improved interface overall. Most designers will wax lyrical on the benefits of plenty of whitespace and how giving content room to breathe can improve the usability of the interface.</p>

<p>The visual density of content within your web-based documents can easily be controlled with an extensive set of CSS properties. However, there are only a few that give entirely predictable results across all browsers:</p>

<ul>
<li><code>font-size</code></li>
<li><code>line-height</code></li>
<li><code>padding</code></li>
<li><code>margin</code></li>
<li><code>width</code></li>
<li><code>height</code></li>
</ul>

<p>Importantly, these properties control both content size and the amount of whitespace that surrounds it. Together these two factors can sway the balance between spacious legibility and the efficient use of limited screen real-estate.</p>

<h2 id="a_demonstration">A demonstration</h2>

<p>Here’s a quick and dirty prototype that I’ve knocked up to demonstrate visual density variance at work. You can vary the density via the buttons at the top, or by resizing your browser window (which will override the former):</p>

<p><a href="http://timhuegdon.com/test-cases/density/">http://timhuegdon.com/test-cases/density/</a></p>

<p>The source code for this example is available here:</p>

<p><a href="http://github.com/nefarioustim/density-demo/">http://github.com/nefarioustim/density-demo/</a></p>

<h2 id="how_it_works">How it works</h2>

<p>In my demo I am applying a class to the root element of the document that controls the level of content density selected by the user. I also repeat those styles within media queries for different client widths to allow denser content on smaller screens—try resizing the browser window to watch it respond.</p>

<p>To make this more maintainable in the future I’d probably invoke those styles through some form of SASS or LESS mix-in to cut down on the obvious duplication of styles. However, be aware that the use of CSS preprocessors like SASS and LESS can complicate things when attempting to get browsers that do not support media queries to detect the styles using a JavaScript polyfill like Respond.js.</p>

<h2 id="summary">Summary</h2>

<p>So there you have it; a simple technique that has a pretty significant impact to the readability of your content. Hey, and the demo is kinda fun to play with too.</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[On HTML element identifiers]]></title>
        <link href="https://nefariousdesigns.co.uk/on-html-element-identifiers.html"/>
        <updated>2011-09-27T17:11:43+08:00</updated>
        <id>https://nefariousdesigns.co.uk/on-html-element-identifiers</id>
        <content type="html"><![CDATA[<p>Back in April 2007, I wrote a short <a href="http://www.flickr.com/photos/nefarioustim/460040199/">article on HTML element identifiers for the .net magazine "Expert Advice" section</a>. I have never republished it online—despite it being 400 words, nicely to the point and suitably succinct—and have long been meaning to reexamine the subject in more detail.</p>

<p>By a total coincidence a discussion in a recent front-end code review and a discussion over the past couple of days on Twitter both relate to the use of HTML element identifiers. The former, a discussion on semantic value and remembering that HTML should not prognosticate styling; the latter, a discussion on the validity of using IDs to target CSS. With both of these considerations I’m going to study the fundamentals of writing good element identifiers within this article.</p>

<!--more-->

<h2 id="whats_an_element_identifier">What’s an element identifier?</h2>

<p>HTML has two element identifiers; the <code>id</code> attribute and the <code>class</code> attribute. These attributes can be applied to most of the elements within a modern HTML document.</p>

<h2 id="what_do_they_do">What do they do?</h2>

<p>The <code>id</code> attribute assigns a name to an element. This name must be unique within the document and each element can have only one.</p>

<p>The <code>class</code> attribute assigns a class or set of classes to an element. Any number of elements may be assigned the same class name or names and each element can have many.</p>

<p>In relationship terms this means IDs and elements are a one-to-one relationship, and classes and elements are a many-to-many relationship. IDs are very much an absolute index system and classes are more of a tag-style classification aide.</p>

<p>Make note of those words: "name" and "classification”. I’ll come back to that in a bit.</p>

<h2 id="mislaid_mastery">Mislaid mastery</h2>

<p>Put in those simple terms it’s all pretty straightforward, and I think that most front-end developers have a good general grasp of their usage. However, it’s the detail that introduces the issues, and if you take time to step back it’s easy to see why:</p>

<p>Element identifiers are the perfect answer for cross-linking other front-end technologies to your HTML. They are the hooks on which to hang your styling and behaviours, and because of this they take on that personality in your mind. This is where so many developers go wrong.</p>

<p>When front-end developers are first introduced to the <code>id</code> and <code>class</code> attributes, it’s often so the identifiers can be targeted in CSS selectors as a means of styling the developers’ documents. They will also inevitably start using them to hook progressive enhancement into their documents via DOM scripting. These are the two most common uses of element identifiers:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">id=</span><span class="s">"site-navigation"</span> <span class="na">class=</span><span class="s">"navigation"</span><span class="nt">&gt;</span>
    …
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nf">#site-navigation</span> <span class="p">{</span>
    <span class="nl">border-bottom</span><span class="p">:</span> <span class="m">2px</span> <span class="nb">solid</span> <span class="no">red</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.navigation</span> <span class="nt">a</span><span class="nd">:focus</span><span class="o">,</span>
<span class="nc">.navigation</span> <span class="nt">a</span><span class="nd">:hover</span><span class="o">,</span>
<span class="nc">.navigation</span> <span class="nt">a</span><span class="nd">:active</span> <span class="p">{</span>
    <span class="nl">outline</span><span class="p">:</span> <span class="m">2px</span> <span class="nb">solid</span> <span class="no">yellow</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">site</span><span class="o">-</span><span class="nx">nav</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="dl">"</span><span class="s2">site-navigation</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">site</span><span class="o">-</span><span class="nx">nav</span><span class="p">.</span><span class="nx">invokeOarsumNavWidget</span><span class="p">();</span>

<span class="c1">// Use some modern browser native DOM + JS win</span>
<span class="kd">var</span> <span class="nx">navCollection</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementsByClassName</span><span class="p">(</span><span class="dl">"</span><span class="s2">navigation</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">navCollection</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">index</span><span class="p">,</span> <span class="nx">array</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Do something to every element</span>
    <span class="c1">// with a class of "navigation"</span>
<span class="p">});</span></code></pre></figure>

<p>Also, if you’ve ever wanted to make use of the <a href="http://isolani.co.uk/blog/javascript/BreakingTheWebWithHashBangs">URI fragment identifier in a non-destructive way</a>, you may have used the ID element identifier instead of the old-skool named anchor (<code><a name="something"></a></code>) approach:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"#navigation"</span><span class="nt">&gt;</span>Skip to navigation<span class="nt">&lt;/a&gt;</span></code></pre></figure>

<p>In each of the above examples, the element identifiers were added specifically to be used by some other language; for styling it is CSS, for dynamic behaviour it is JavaScript, and for linking it is <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Identifier">the URI RFC 3305</a>. However, that association also occurs psychologically in our minds as developers and we often have trouble seeing past it.</p>

<h2 id="names_and_classifications">Names and classifications</h2>

<p>Back to those "name" and "classification” descriptions:</p>

<p>It seems we have carelessly forgotten the fact that element identifiers are a feature of HTML and not the other languages that use them as targets. We should be using them as they were originally intended; to name and classify the content within our mark-up.</p>

<p>We already use HTML elements to describe the content which they contain. This is the very heart of semantic HTML and should result in content like heading text being wrapped in <code>h1</code>-<code>h6</code> tags; lists in <code>ul</code>, <code>ol</code>, or <code>dl</code> tags; and tabular data in <code>table</code> elements. Since IDs and classes are attributes of these elements, we should use them to improve the semantic value of their hosts and provide further descriptiveness or context.</p>

<p>If we return to our previous list example, the following mark-up is reasonably semantic:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/index.html"</span><span class="nt">&gt;</span>Home<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/about/"</span><span class="nt">&gt;</span>About<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/"</span><span class="nt">&gt;</span>Blog<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/archive/"</span><span class="nt">&gt;</span>Archive<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/contact/"</span><span class="nt">&gt;</span>Contact<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>However, we can improve it further by giving it some context with an ID:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">id=</span><span class="s">"site-navigation"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/index.html"</span><span class="nt">&gt;</span>Home<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/about/"</span><span class="nt">&gt;</span>About<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/"</span><span class="nt">&gt;</span>Blog<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/archive/"</span><span class="nt">&gt;</span>Archive<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/contact/"</span><span class="nt">&gt;</span>Contact<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>Now it’s more obvious what this list of links actually is without seeing it styled up and rendered in the browser.</p>

<p>We could provide even more information with a single class:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">id=</span><span class="s">"site-navigation"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/index.html"</span> <span class="na">class=</span><span class="s">"current-page"</span><span class="nt">&gt;</span>Home<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/about/"</span><span class="nt">&gt;</span>About<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/"</span><span class="nt">&gt;</span>Blog<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/archive/"</span><span class="nt">&gt;</span>Archive<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/contact/"</span><span class="nt">&gt;</span>Contact<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>I’m sure most web developers have done something similar in the past, but it’s a very good example of applying context with a class the <em>right</em> way. The HTML now gives us a very good description of the content it contains. In fact, you now only need glance at this markup to understand its function.</p>

<p>Let’s take it a little further. Imagine we have several types of navigation in the page; we can better describe these elements by <em>classifying</em> them as navigation:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">id=</span><span class="s">"site-navigation"</span> <span class="na">class=</span><span class="s">"navigation"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/index.html"</span> <span class="na">class=</span><span class="s">"current-page"</span><span class="nt">&gt;</span>Home<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/about/"</span><span class="nt">&gt;</span>About<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/"</span><span class="nt">&gt;</span>Blog<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/archive/"</span><span class="nt">&gt;</span>Archive<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/contact/"</span><span class="nt">&gt;</span>Contact<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>

<span class="nt">&lt;p</span> <span class="na">id=</span><span class="s">"breadcrumb"</span> <span class="na">class=</span><span class="s">"navigation"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"/index.html"</span><span class="nt">&gt;</span>Home<span class="nt">&lt;/a&gt;</span>
    <span class="ni">&amp;gt;</span> <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"/blog/"</span><span class="nt">&gt;</span>Blog<span class="nt">&lt;/a&gt;</span>
    <span class="ni">&amp;gt;</span> My Blog Post
<span class="nt">&lt;/p&gt;</span>

<span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">"page-footer"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;p&gt;</span>© 2011 Oarsum Corp, all rights reserved.<span class="nt">&lt;/p&gt;</span>
    <span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"navigation"</span><span class="nt">&gt;</span>
        <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"terms.html"</span><span class="nt">&gt;</span>Terms and conditions<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
        <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"privacy.html"</span><span class="nt">&gt;</span>Privacy policy<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;/ul&gt;</span>
<span class="nt">&lt;/div&gt;</span></code></pre></figure>

<p>Simple, right? We’re using the element identifiers to improve the semantics of the markup and gaining improved readability as a side-effect. What’s more the added context can be targeted by whatever technology you so desire.</p>

<h2 id="anti_patterns">Anti-patterns</h2>

<p>I’m pretty confident that most web developers will end up with markup similar to this without necessarily understanding my point. To that end, let’s take a look at some common anti-patterns (or misuses) that may go some way towards forwarding that understanding:.</p>

<h3 id="the_clearfix_class">The "clearfix" class</h3>

<p>Way back in 2004 [ya rly!], <a href="http://www.positioniseverything.net/easyclearing.html">Tony Aslett and Position is Everything published a clever method for containing floats</a> that involved using the pseudo <code>:after</code> selector to insert some content and use that as an anchor for <code>clear: both</code>. It was a clever technique and was quickly adopted by the community, often incorrectly bound to a class entitled "clearfix":</p>

<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.clearfix</span><span class="nd">:after</span> <span class="p">{</span>
    <span class="nl">content</span><span class="p">:</span> <span class="s1">"."</span><span class="p">;</span>
    <span class="nl">display</span><span class="p">:</span> <span class="nb">block</span><span class="p">;</span>
    <span class="nl">height</span><span class="p">:</span> <span class="m">0</span><span class="p">;</span>
    <span class="nl">clear</span><span class="p">:</span> <span class="nb">both</span><span class="p">;</span>
    <span class="nl">visibility</span><span class="p">:</span> <span class="nb">hidden</span><span class="p">;</span>
<span class="p">}</span>

<span class="c">/* IE targeted property */</span>
<span class="nc">.ie</span> <span class="nc">.clearfix</span> <span class="p">{</span>
    <span class="py">zoom</span><span class="p">:</span> <span class="m">1</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<p>Quite apart from the somewhat erroneous name (it should really be "contain-float") this is absolutely the wrong place to be addressing this sort of styling issue. A styling-specific meta-class such as this is no different to writing a class entitled "red-text" or "big-blue-heading". In my opinion, the small amount of repetition it saves you in the CSS is not worth the non-semantic clutter in your HTML.</p>

<p>There are several ways to contain floats in CSS and the method you should use absolutely depends on the context. What’s more, some of those methods are a <em>single CSS property declaration</em>. For this reason, declaring a class of "clearfix" and implementing a single float clearing solution within it is actually potentially detrimental to the overall efficiency of your CSS.</p>

<p>It’s worth noting also that providing a meta-class tool like this results in a disassociation between the problem and the "fix". You’re likely to experience maintenance issues when you change any float behaviours and the containing mechanism is abstracted from the target’s styles. In addition to this you’re likely to find developers over using the solution to address problems they’ve introduced themselves.</p>

<h3 id="the_hide_offscreen_class">The "hide-offscreen" class</h3>

<p>When developers are aware of accessibility issues, and are attempting to provide textual description for otherwise potentially inaccessible content, you will often find a class that looks something like this:</p>

<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.hide-offscreen</span> <span class="p">{</span>
    <span class="nl">text-indent</span><span class="p">:</span> <span class="m">-999em</span><span class="p">;</span>
    <span class="nl">font-size</span><span class="p">:</span> <span class="m">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="c">/* or */</span>

<span class="nc">.hide-offscreen</span> <span class="p">{</span>
    <span class="nl">position</span><span class="p">:</span> <span class="nb">absolute</span><span class="p">;</span>
    <span class="nl">left</span><span class="p">:</span> <span class="m">-999em</span><span class="p">;</span>
    <span class="nl">font-size</span><span class="p">:</span> <span class="m">0</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<p>This moves text off the screen, thus making it invisible for those not using a screenreader. This is preferable to <code>display: none</code> (which you might use to hide content from <strong>all</strong> users) because the content is only hidden within the browser viewport, but not removed from the complete rendering of the DOM.</p>

<p>However, what we’ve done here is define our CSS <em>first</em> and then apply that classification to our content. We’re supposed to be doing it the other way around. This class is unhelpful in describing the content that it wraps because it describes the behaviour the CSS should apply. This results in it providing little explanation of the developer’s intent, resulting in HTML like:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"hide-offscreen"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"#navigation"</span><span class="nt">&gt;</span>Skip to navigation<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>Not a good class at all. This is an improvement:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"accessibility navigation"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"#navigation"</span><span class="nt">&gt;</span>Skip to navigation<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>I've added the accessibility class here to signal intent: it's navigation for improving accessibility. I could have been more specific here, but overall I predict a high likelihood I'll want to signal a similar intent on other features within my document.</p>

<p>However, the double class will cause problems if you need to target both classes at once (e.g. <code>.accessibility.navigation {}</code>) in IE6. That browser will only target the final class in the selector. To fix this, you could combine the classes to create a new one:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"accessibility-navigation accessibility navigation"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"#navigation"</span><span class="nt">&gt;</span>Skip to navigation<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>Or a less ugly solution would be to include an ID on the navigation:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">id=</span><span class="s">"header-skip-links"</span> <span class="na">class=</span><span class="s">"accessibility navigation"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"#navigation"</span><span class="nt">&gt;</span>Skip to navigation<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>Or to use a wrapping element and target with the descendant selector:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"accessibility"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"navigation"</span><span class="nt">&gt;</span>
        <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"#navigation"</span><span class="nt">&gt;</span>Skip to navigation<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;/ul&gt;</span>
<span class="nt">&lt;/div&gt;</span></code></pre></figure>

<p>Here we’ve named the content and classified it well. It would be difficult to argue that we haven’t provided any targets for styling or behaviours now too. Unfortunately we’ve had to jump through hoops for IE6 and have broken our rule of changing the HTML for the CSS, but I just wanted to illustrate that there are more options available given a little thought.</p>

<h3 id="avoiding_repetition">Avoiding repetition</h3>

<p>It’s entirely fair to argue that both the anti-patterns above avoid repetition within the CSS itself. However, this shouldn’t necessarily be the <em>only</em> reason to adopt one of these types of solution. There are other options available to us to abstract away this kind of anti-<a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> maintenance nightmare:</p>

<ul>
<li><a href="http://lesscss.org/#-mixins">LESS Mix-ins</a></li>
<li><a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixins">SASS Mix-ins</a></li>
<li>Place the CSS higher up the cascade</li>
</ul>

<p>Indeed most CSS preprocessors will allow you similar functionality as it is clearly a "missing feature" of CSS as a whole. The alternative, of course, is to make your "fix" a part of the relevant cascade, so that all selectors beneath inherit that behaviour.</p>

<h2 id="a_nice_example">A nice example</h2>

<p>A really nice example of classification is this <a href="http://mikewest.org/2010/02/an-accessible-pagination-pattern">simple design pattern for pagination</a>:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;p</span> <span class="na">id=</span><span class="s">"paginglabel"</span> <span class="na">class=</span><span class="s">"audible"</span><span class="nt">&gt;</span>Pagination<span class="nt">&lt;/p&gt;</span>
<span class="nt">&lt;ul</span> <span class="na">role=</span><span class="s">"navigation"</span> <span class="na">aria-labelledby=</span><span class="s">"paginglabel"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"#"</span><span class="nt">&gt;&lt;span</span> <span class="na">class=</span><span class="s">"audible"</span><span class="nt">&gt;</span>%TYPE% Page<span class="nt">&lt;/span&gt;</span>1<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"#"</span> <span class="na">rel=</span><span class="s">"prev"</span><span class="nt">&gt;&lt;span</span> <span class="na">class=</span><span class="s">"prev"</span><span class="nt">&gt;</span>Previous<span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">"audible"</span><span class="nt">&gt;</span>: %TYPE% Page<span class="nt">&lt;/span&gt;&lt;/span&gt;</span>2<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;p&gt;&lt;span</span> <span class="na">class=</span><span class="s">"audible"</span><span class="nt">&gt;</span>You're currently reading %TYPE% page <span class="nt">&lt;/span&gt;</span>3<span class="nt">&lt;/p&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"#"</span> <span class="na">rel=</span><span class="s">"next"</span><span class="nt">&gt;&lt;span</span> <span class="na">class=</span><span class="s">"next"</span><span class="nt">&gt;</span>Next<span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">"audible"</span><span class="nt">&gt;</span>: %TYPE% Page<span class="nt">&lt;/span&gt;&lt;/span&gt;</span>4<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"#"</span><span class="nt">&gt;&lt;span</span> <span class="na">class=</span><span class="s">"audible"</span><span class="nt">&gt;</span>%TYPE% Page <span class="nt">&lt;/span&gt;</span>5<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>Here we see the "audible" class describing content that should only be exposed to non-visual devices, such as screen readers and content scrapers (like search engine spiders). This is a good classification of a <em>subset</em> of the content.</p>

<p>It’s also worth noting the good use of <a href="http://www.w3.org/WAI/intro/aria">WAI-ARIA</a> roles and the <code>rel</code> attributes on the next and previous links. These are two other ways you can improve the semantics of your HTML and abstract away some of the classification to a more suitable annotation system.</p>

<h2 id="clean_code">Clean Code</h2>

<p>Markup languages can often add to the obfuscation of code simply by their structure. If we use the element identifiers as they are intended we should end up reducing the overhead to <a href="http://en.wikipedia.org/wiki/Grok">grok</a> relatively clean code.</p>

<p>Clean code is, amongst other things:</p>

<ul>
<li>Readable</li>
<li>Understandable</li>
<li>Predictable</li>
<li>Maintainable</li>
</ul>

<p>Use of element identifiers as semantic descriptors improves each one of these points. This is especially obvious when dealing with somebody else’s code, and in a team environment I personally feel it is imperative to include this in coding standards and best practices.</p>

<p>Good use of names and classification is just as effective as good commenting. When the code is effectively self documenting through its element identifier annotation, the need for commenting is significantly reduced.</p>

<h2 id="on_css_best_practice_proposals">On CSS best practice proposals</h2>

<p>Now that I’ve covered the "hows" and "whys", I’d like to highlight why I think certain recommendations for CSS best practice directly contravene the correct use of element identifiers:</p>

<p>There has been some discussion within the front-end community regarding the use of IDs when targeting CSS. The ID attribute has particularly strong specificity in CSS, due to its uniqueness. When used incorrectly, it can cause maintenance problems and specificity bugs. However, the idea that targeting the ID property with CSS should be considered harmful—as seen in CSSLint, for example—is extreme to say the least.</p>

<p>It <em>is</em> reasonably simple to clobber other rules on an element by incorporating an ID in the selector, but this should really be an <em>expected</em> outcome. The use of an ID in a selector should denote the intent that the rule targets only a single occurrence of something within the page. If that is not what the developer intended, then they’ve wildly misunderstood the need for that selector. Certainly it makes sense that targeting an ID should be considered harmful when the developer actually meant to target something less specific, but then that’s just using CSS properly, isn’t it?</p>

<p>The argument that it is less valid to target IDs when working in a truly modular environment is even worse. A truly modular front-end environment will always require instance targeting alongside classification targeting. Sure, it’s likely to be the minority of situations, but there will always be cases in your system where it makes much more sense to target an ID than a class, and since they’re already in place on your HTML by this point [they are, right? We’ve already talked about this. If they’re not, go back and read it again.] you don’t have to worry about your CSS enforcing your HTML.</p>

<p>The developers that make these sorts of recommendations must be aware that they, as leaders in their field, have a responsibility not to mis-sell their solutions. Problems born of misuse do not emphasise an inherent flaw with the technology but perhaps an inherent flaw with the expertise of the user. As an exercise in correlation, it’s worth noting that Chefs do not veto the use of sharp knives because someone once cut their fingertip off with one.</p>

<h2 id="summary">Summary</h2>

<p>HTML, CSS, and JavaScript are separate technologies. They are quite tightly related in the world of client-side development, but they should always remain decoupled. The element identifier is an artefact of HTML and should therefore not attempt to predict the hooks required for other technologies; it should simply be a property of effective semantic markup.</p>

<p>Further to this, avoiding the use of an element identifier, simply because it is so often misused by otherwise able front-end developers, is—at the risk of being blunt—ridiculous. Be proud of your HTML, spend as much time perfecting it as you would on any other language, and, most of all, don’t pollute it with the litter produced by a solution, in a related language, that lacks finesse.</p>

<h3 id="final_note">Final note</h3>

<p>I realise, however, that—despite my banging on about it—there are some developers you just can’t reach. As Jared Spool so eloquently puts it in his blog post, "<a href="http://www.uie.com/brainsparks/2011/07/08/beans-and-noses/">Beans and noses</a>":</p>

<blockquote>
  <p>No matter how much you try, you can’t stop people from sticking beans up their nose.</p>
</blockquote>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Sniff my browser: The Modernizr inadequacy]]></title>
        <link href="https://nefariousdesigns.co.uk/sniff-my-browser-the-modernizr-inadequacy.html"/>
        <updated>2011-05-17T20:03:47+08:00</updated>
        <id>https://nefariousdesigns.co.uk/sniff-my-browser-the-modernizr-inadequacy</id>
        <content type="html"><![CDATA[<p>I’m currently involved in a project to write a fairly extensive set of best practices for front-end development. Alongside myself, this project includes input from a fair cross-section of my peers in the front-end development community. These best practices will be implemented alongside a coding standard as standards for development within the organisation I work for, and hopefully many other organisations when they are published.</p>

<p>Of all the standards that a front-end team might want to implement, those that concern the identification and graceful degradation of cross-browser feature sets can be the hardest to define.</p>

<p>With that in mind, I’ve been poking around the front-end community looking for possible solutions. By far the most common approach—and one that gains an astounding level of attention in the community—is to implement <a href="http://www.modernizr.com/">Modernizr</a>, a JavaScript feature sniffer created by <a href="http://farukat.es/">Faruk Ateş</a>, <a href="http://paulirish.com/">Paul Irish</a> and <a href="http://alexsexton.com/">Alex Sexton</a>.</p>

<p>Unfortunately, despite my respect for the developers involved, I just can’t advocate Modernizr as a solution. Let me explain why; but first, let’s revisit some concepts that are going to be quite relevant…</p>

<!--more-->

<h2 id="the_web_standards_trifle">The web standards trifle</h2>

<p>The separation of structure, presentation, and dynamic behaviour is imperative to web standards. To that end, Andy “Malarkey” Clarke wrote a fantastic post detailing a method he liked to use to explain this fact to clients. He entitled it “<a href="http://www.stuffandnonsense.co.uk/archives/web_standards_trifle.html">the web standards trifle</a>”.</p>

<p>In Andy’s metaphor, the separation of concerns can be imagined as follows:</p>

<ol>
<li><p><strong>Sponge</strong></p>

<p>This layer is your content, marked-up with well structured and valid semantic HTML. This HTML provides more information about each piece of content and allows any device reading the code to output as appropriate.</p></li>
<li><p><strong>Fruity jelly</strong></p>

<p>This is your presentational layer. This separates all your presentational code into CSS, potentially allowing a user to override it with their own, or for you to serve something different based on context, e.g. a print or mobile stylesheet.</p></li>
<li><p><strong>Custard</strong></p>

<p>This is the layer that accommodates any on-page behaviours. In the world of web standards we use this layer to progressively enhance our HTML and CSS layers with more interactive magic. I’ll come back to this later.</p></li>
</ol>

<p>The true virtue of this divide is that the presentational (jelly) and behavioural (custard) layers can potentially be removed or overridden without affecting each other, or the content and markup beneath. This is hugely important if we want our websites to maintain client agnosticism and improve accessibility.</p>

<h2 id="progressive_enhancement">Progressive enhancement</h2>

<p>Following the publication of this article there have been several suggestions that I explain <a href="http://nefariousdesigns.co.uk/archive/2010/10/object-oriented-javascript-follow-up-part-1-method/#graceful_degradation">the difference between <em>graceful degradation</em> and <em>progressive enhancement</em></a>. Suffice to say, this is something I have covered previously in another article.

<h2 id="browser_vs_feature_sniffing">Browser vs. Feature Sniffing</h2>

<p>Browser “sniffing” is the act of attempting to discern a user’s browser by some means. This “awareness” can then be used in conditional code to control output or interaction for a specific browser. This technique was used a great deal in days of yore, when browsers had very different rendering engines and didn’t all conform to web standards. However, it was only ever really required in JavaScript.</p>

<p>The old school way:</p>


<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="k">if</span> <span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">all</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// IE4</span>
    <span class="nx">height</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">offsetHeight</span><span class="p">;</span>
<span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">layers</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// NN4</span>
    <span class="nx">height</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nx">innerHeight</span><span class="p">;</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// other</span>
    <span class="nx">height</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>


<h3 id="not_a_good_solution">Not a good solution</h3>

<p>There are problems with the method used above; for one thing, it is not the most direct method of identifying a browser. However, putting that aside for the moment, there are issues even with the <em>theory</em> of browser sniffing:</p>

<p>It’s quite obvious that browser sniffing does not scale. As new browsers are released, the sniffing code will need updating.</p>

<p>To make matters worse, many manufacturers developed their browsers to identify themselves incorrectly to get around <em>legacy</em> browser sniffing code. This ultimately meant that sometimes browsers were misidentified.</p>

<p>Ultimately browser sniffing is not a good solution. If you adopt it, you will usually end up maintaining separate streams of development whenever you need to add or update features. There are ways to mitigate that pain, but what if there was a better solution?</p>

<h3 id="feature_sniffing">Feature sniffing</h3>

<p>A more scalable approach is to use object detection in JavaScript to discover if a feature is available before you use it. An example of this might be:</p>


<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="k">if</span> <span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">element</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="nx">selectors</span><span class="p">);</span>
<span class="p">}</span></code></pre></figure>


<p>The obvious advantage here is that it is browser agnostic; there are no assumptions as to which browser is involved at all. Using this technique, we overcome the scalability and maintenance headaches incurred through browser sniffing, and we can develop for graceful degradation from the outset.</p>

<h2 id="css_is_a_dsl_that_lacks_features">CSS is a DSL that lacks features</h2>

<p>Now, that’s all very well and good when we’re talking about JavaScript, but what happens when we need to affect the presentation layer?</p>

<p>CSS is a very simple <em>domain specific language</em> (DSL) that functions as a series of rules that override each other in a variety of ways (the cascade). There is no mechanism to detect a specific feature or a user-agent; only <a href="http://www.w3.org/TR/CSS2/media.html">media types</a> and potentially the odd CSS hack where a user-agent has imperfectly implemented an interpreter. There are also no conditionals; you just have to use the cascade to provide alternatives based on specificity or even just source order.</p>

<p>With these limitations, it is <strong>impossible</strong> to implement either browser <em>or</em> feature sniffing in CSS. This means we need to find an alternative method to affect the cascade based on the user’s feature set.</p>

<h2 id="the_modernizr_method">The Modernizr method</h2>

<p>Step in <a href="http://www.modernizr.com/">Modernizr</a>. In the words of <a href="http://www.modernizr.com/docs/">the documentation</a>:</p>

<blockquote>
  <p>Modernizr aims to bring an end to the UA sniffing practice. Using feature detection is a much more reliable mechanic to establish what you can and cannot do in the current browser, and Modernizr makes it convenient for you in a variety of ways:</p>

<ol>
<li><p>It tests for over 20 next-generation features, all in a matter of milliseconds.</p></li>
<li><p>It creates a JavaScript object (named Modernizr) that contains the results of these tests as boolean properties.</p></li>
<li><p>It adds classes to the <code>html</code> element that explain precisely what features are and are not natively supported.</p></li>
</ol>
</blockquote>

<p>Following along so far? For the most part, that all seems fairly good. What’s more, Modernizr is definitely being pushed as the solution of choice amongst the front-end community:</p>

<ul>
<li><a href="http://diveintohtml5.org/detect.html">Mark Pilgrim’s Dive into HTML5 “Detection” chapter</a></li>
<li><a href="http://www.alistapart.com/articles/taking-advantage-of-html5-and-css3-with-modernizr/">Faruk’s “Taking Advantage of HTML5 and CSS3 with Modernizr” on A List Apart</a></li>
<li><a href="http://webdesignernotebook.com/css/how-to-use-modernizr/">Web Designer Notebook: How to use Modernizr</a></li>
<li><a href="http://blogs.sitepoint.com/build-an-awesome-image-gallery-with-jquery-modernizr-and-css3/">Image Gallery tutorial on Sitepoint</a></li>
</ul>

<p>So with all that in mind, let’s go back to why I will not be recommending Modernizr as a best practice:</p>

<h3 id="sniffing_css_features_with_javascript">Sniffing CSS features with JavaScript</h3>

<p>The real issue is that Modernizr uses JavaScript to do the feature sniffing. This method is absolutely fine if we were only looking to test for the features in JavaScript. However, Modernizr is marketed on its ability to detect CSS3 and HTML5 features so that you can write gracefully degrading CSS:</p>

<blockquote>
  <p>Modernizr is a small and simple JavaScript library that helps you take advantage of emerging web technologies (CSS3, HTML 5) while still maintaining a fine level of control over older browsers that may not yet support these new technologies.</p>
</blockquote>

<p>If Modernizr had sold itself as a JavaScript feature sniffing solution that also detected CSS features perhaps I could be more forgiving. In that context, it would be the developers’ responsibility to use Modernizr correctly. However, since the Modernizr site and documentation are selling it <em>specifically</em> as a CSS feature sniffing solution, for primary use within CSS, the error is clearly with the Modernizr team themselves.</p>

<p>It’s all down to the final step outlined in the documentation I quoted earlier:</p>

<blockquote>
 It adds classes to the <code>html</code> element that explain precisely what features are and are not natively supported.
</blockquote>

<p>Modernizr uses JavaScript to add those classes to the <code>html</code> element; one for each of the features detected in the current browser. If we examine the generated source we see the following:</p>


<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">"en"</span> <span class="na">dir=</span><span class="s">"ltr"</span> <span class="na">id=</span><span class="s">"modernizr-com"</span> <span class="na">class=</span><span class="s">" js flexbox canvas
canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb
hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize
borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns
cssgradients cssreflections csstransforms csstransforms3d csstransitions
fontface video audio localstorage sessionstorage webworkers applicationcache
svg inlinesvg smil svgclippaths"</span><span class="nt">&gt;</span></code></pre></figure>


<p>When I first saw that, I was horrified. Not only is it ridiculously cluttered, it also feels decidedly unsemantic and looks like a terminal case of <a href="http://www.sitekin.com/blogdetail/avoid_CSS_Classitis">classitis</a>. However, let’s try to be pragmatic here; it’s a means to an end, potentially a minor side-effect to a process that will win us some power in the bigger picture. In fact, it’s one step on from <a href="http://paulirish.com/2009/avoiding-the-fouc-v3/">Paul Irish’s proposed work around to the FOUC (flash of unstyled content)</a> which I’ve advocated as a reasonable fallback to marking progressively enhanced objects with an “enhanced” class.</p>

<h3 id="making_use_of_the_classes">Making use of the classes</h3>

<p>The Modernizr method allows you to assign styles based on these new classes on the document’s root element like so (example lifted from the Modernizr docs):</p>


<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nt">button</span><span class="nc">.glossy</span> <span class="p">{</span>
   <span class="nl">background</span><span class="p">:</span> <span class="m">#ccc</span> <span class="sx">url(gloss.png)</span> <span class="m">50%</span> <span class="m">50%</span> <span class="nb">repeat-x</span><span class="p">;</span>
<span class="p">}</span>
<span class="nc">.cssgradients</span> <span class="nt">button</span><span class="nc">.glossy</span> <span class="p">{</span>
   <span class="nl">background</span><span class="p">:</span> <span class="m">#ccc</span> <span class="n">-webkit-gradient</span><span class="p">(</span><span class="n">linear</span><span class="p">,</span> <span class="nb">left</span> <span class="nb">top</span><span class="p">,</span> <span class="nb">left</span> <span class="nb">bottom</span><span class="p">,</span>
         <span class="n">from</span><span class="p">(</span><span class="n">rgba</span><span class="p">(</span><span class="m">255</span><span class="p">,</span><span class="m">255</span><span class="p">,</span><span class="m">255</span><span class="p">,</span> <span class="m">.4</span><span class="p">)),</span>
         <span class="n">color-stop</span><span class="p">(</span><span class="m">0.5</span><span class="p">,</span> <span class="n">rgba</span><span class="p">(</span><span class="m">255</span><span class="p">,</span><span class="m">255</span><span class="p">,</span><span class="m">255</span><span class="p">,</span> <span class="m">.7</span><span class="p">)),</span>
         <span class="n">color-stop</span><span class="p">(</span><span class="m">0.5</span><span class="p">,</span> <span class="n">rgba</span><span class="p">(</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span> <span class="m">.2</span><span class="p">)),</span>
         <span class="n">to</span><span class="p">(</span><span class="n">rgba</span><span class="p">(</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span> <span class="m">.1</span><span class="p">)));</span>
<span class="p">}</span>
<span class="nc">.cssgradients</span> <span class="nt">button</span><span class="nc">.glossy</span><span class="nd">:hover</span> <span class="p">{</span>
   <span class="nl">background-color</span><span class="p">:</span> <span class="m">#fff</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>


<p>Here we can see that <code>button.glossy</code> is first defined with a standard <code>png</code> as its background. The Modernizr-added <code>.cssgradients</code> class is then used to increase specificity and assign a WebKit gradient instead.</p>

<p>What happens if we approach the problem <em>without</em> the .cssgradients class:</p>

<p>CSS allows us to define a property twice in the same rule. It also contains built-in error handling that will ignore a property it doesn’t understand; so browsers that do not understand <code>-webkit-gradient()</code>, for example, will simply ignore a property that uses it. This allows us to progressively enhance our CSS like so:</p>


<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nt">button</span><span class="nc">.glossy</span> <span class="p">{</span>
   <span class="nl">background</span><span class="p">:</span> <span class="m">#ccc</span> <span class="sx">url(gloss.png)</span> <span class="m">50%</span> <span class="m">50%</span> <span class="nb">repeat-x</span><span class="p">;</span>
   <span class="nl">background</span><span class="p">:</span> <span class="m">#ccc</span> <span class="n">-webkit-gradient</span><span class="p">(</span><span class="n">linear</span><span class="p">,</span> <span class="nb">left</span> <span class="nb">top</span><span class="p">,</span> <span class="nb">left</span> <span class="nb">bottom</span><span class="p">,</span>
         <span class="n">from</span><span class="p">(</span><span class="n">rgba</span><span class="p">(</span><span class="m">255</span><span class="p">,</span><span class="m">255</span><span class="p">,</span><span class="m">255</span><span class="p">,</span> <span class="m">.4</span><span class="p">)),</span>
         <span class="n">color-stop</span><span class="p">(</span><span class="m">0.5</span><span class="p">,</span> <span class="n">rgba</span><span class="p">(</span><span class="m">255</span><span class="p">,</span><span class="m">255</span><span class="p">,</span><span class="m">255</span><span class="p">,</span> <span class="m">.7</span><span class="p">)),</span>
         <span class="n">color-stop</span><span class="p">(</span><span class="m">0.5</span><span class="p">,</span> <span class="n">rgba</span><span class="p">(</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span> <span class="m">.2</span><span class="p">)),</span>
         <span class="n">to</span><span class="p">(</span><span class="n">rgba</span><span class="p">(</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span><span class="m">0</span><span class="p">,</span> <span class="m">.1</span><span class="p">)));</span>
<span class="p">}</span>
<span class="nt">button</span><span class="nc">.glossy</span><span class="nd">:hover</span> <span class="p">{</span>
   <span class="nl">background-color</span><span class="p">:</span> <span class="m">#fff</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>


<p>However, because we can no longer target the <code>.cssgradients</code> class specifically, we cannot target the <code>button:hover</code> styles only when CSS gradients are detected. Clearly this is an issue we’ll have to find some way around and is exactly what Modernizr is attempting to solve.</p>

<p>This all seems as if Modernizr is giving us a great deal of power, however, it comes with a significant cost.</p>

<h2 id="dependency_on_javascript_is_bad">Dependency on JavaScript is bad</h2>

<p>Fellow web developer and good friend <a href="http://isolani.co.uk/">Mike Davies</a> wrote a really great article containing a good summary of <a href="http://isolani.co.uk/blog/javascript/DisablingJavaScriptAskingTheWrongQuestion#javascript-obstacles">obstacles potentially preventing JavaScript from executing</a> back in October 2010. This followed a somewhat presumptuous post by <a href="http://www.nczonline.net/">Nicholas Zakas</a> on the YDN regarding the <a href="http://developer.yahoo.com/blogs/ydn/posts/2010/10/how-many-users-have-javascript-disabled/">number of users with JavaScript disabled</a>.</p>

<p>In short, there are a large number of obstacles that can affect the execution—or even rewrite the source of—JavaScript included in your pages. Hence, dependancy on JavaScript is bad because it introduces many significant points of failure.</p>

<p>As an example of <em>why</em> dependency on JavaScript can be catastrophic, I recommend you read another of Mike’s posts on <a href="http://isolani.co.uk/blog/javascript/BreakingTheWebWithHashBangs">Gawker’s JavaScript dependent URIs and how it broke their sites quite considerably</a>. It’s worth noting that the Gawker sites have since seen the error of their ways and are <a href="http://kotaku.com/5800365/the-first-of-many-updates-to-kotakucom-design-is-live-right-now">attempting to fix the damage</a>.</p>

<h3 id="styling_dependant_on_javascript">Styling dependant on JavaScript</h3>

<p>By adding styles that are specific to classes that have been inserted with JavaScript, we are making those styles dependant on JavaScript. This means those styles will fail to apply if JavaScript itself has been disabled or, more commonly, the JavaScript file applying the classes has failed to load or execute successfully due to one of the reasons above. In essence, we may just as well add those styles with JavaScript directly because we’ve already broken the web standards separation of concerns.</p>

<p>Do we really want to remove the majority of CSS items covered by Modernizr if the Modernizr JavaScript include fails for some reason?</p>

<p>It would only be the feature-sniff-dependant CSS rules that would fail, since those classes would now be missing. Potentially this only means the loss of a few nice in-browser rendering optimisations. However, it also means there is a significant loss in the overall structure of specificity within your stylesheets, which could easily cascade unintended effects through to other elements. This could easily result in some content being styled to be unreadable, or worse, incorrectly hidden. This would be very bad indeed.</p>

<h2 id="alternative_solutions">Alternative solutions</h2>

<p>Modernizr is clearly unfit for purpose. If it were simply a JavaScript feature sniffing library for use <em>only</em> in JavaScript, it would be a suitable solution although only really useful for JavaScript progressive enhancement.</p>

<p>With that in mind, what other options are available that allow us to target our CSS?</p>

<h3 id="server_side_browser_sniffing">Server-side browser sniffing</h3>

<p>We could browser sniff on the server and add a class to the <code>html</code> element as we generate the HTML that is delivered in the HTTP response. This could result in something like the following:</p>


<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">"en"</span> <span class="na">dir=</span><span class="s">"ltr"</span> <span class="na">class=</span><span class="s">"firefox"</span><span class="nt">&gt;</span></code></pre></figure>


<p>This means we can target CSS with the <code>.firefox</code> class in much the same way that we used the feature classes that Modernizr provided. There is no way for us to perform feature sniffing on the server; the best we could offer is a feature lookup based on the user-agent string that we’ve used to sniff the browser, but that would ultimately still be browser sniffing.</p>

<p>In fact, the best browser sniffing solution would allow us a little more flexibility on browser versions:</p>


<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">"en"</span> <span class="na">dir=</span><span class="s">"ltr"</span> <span class="na">class=</span><span class="s">"moz ff ff3-6"</span><span class="nt">&gt;</span></code></pre></figure>


<p>Note I’ve added several classes this time; one for the rendering engine, one for the browser, and one that contains the major and minor versions. This would allow us more specificity.</p>

<p style="padding: 10px; background: #fee; border: 1px solid #c00;"><strong>Update:</strong> Matthew Pennell has written an interesting post on <a href="http://www.thewatchmakerproject.com/blog/no-more-css-hacks-browser-sniffing-with-htaccess/">server-side browser sniffing with .htaccess and environment variables</a>. Definitely worth a read.</p>

<h4 id="cache_issues">Cache issues</h4>

<p>However, server-side browser sniffing means that you’ll run into issues if your pages are publicly cacheable. This server-side solution results in a different HTTP response (the HTML) for each differing browser.</p>

<p>If you utilise any intermediary caching (<a href="http://www.squid-cache.org">Squid</a>, <a href="http://www.varnish-cache.org">Varnish</a>, or a custom origin CDN) for static pages, and you use server-side browser detection, you need to make sure those caches don’t inadvertently send the wrong content to the wrong browser. To do this you’ll need to <code>Vary: User-Agent</code> header in the HTTP response. This instructs any intermediary caches to store multiple copies of the page (one for each <code>User-Agent</code> string that it sees) and to inspect the incoming <code>User-Agent</code> string when looking for cached responses to the current request.</p>

<h3 id="ie_targeting_with_conditional_comments">IE targeting with conditional comments</h3>

<p>If we’re entirely honest with ourselves as web developers, we can probably admit that the majority of woes we experience in CSS are as a direct result of features that any given version of Internet Explorer has not implemented. In fact, I regularly interview developers who advocate maintaining a separate stylesheet for IE that is included through the use of IE’s conditional comments. Having attempted to use this method in the past, I can confidently say that it is a maintenance nightmare and quickly becomes pretty unmanageable.</p>

<p>A better technique would be to adopt conditional comments to add IE specific classes in much the same way we have with Modernizr or server-side browser sniffing. This method was first proposed by none other than Paul Irish back in 2008 in his article "<a href="http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/">Conditional stylesheets vs. CSS hacks? Answer: neither</a>". With that method, our <code>html</code> element would look like this:</p>


<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="c">&lt;!--[if IE ]&gt;
&lt;html lang="en" dir="ltr" class="ie"&gt;
&lt;![endif]--&gt;</span>
<span class="c">&lt;!--[if !IE]&gt;--&gt;</span>
<span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">"en"</span> <span class="na">dir=</span><span class="s">"ltr"</span><span class="nt">&gt;</span>
<span class="c">&lt;!--&lt;![endif]--&gt;</span></code></pre></figure>


<p>This looks a bit odd, and often (for the true markup perfectionist) takes a bit of getting used to. However, it does give us what we need without requiring JavaScript or multiple cache versions.</p>

<p>We can even make it more specific if we so desire:</p>


<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="c">&lt;!--[if lt IE 7 ]&gt;
&lt;html lang="en" dir="ltr" class="ie ie6"&gt;
&lt;![endif]--&gt;</span>
<span class="c">&lt;!--[if IE 7 ]&gt;
&lt;html lang="en" dir="ltr" class="ie ie7"&gt;
&lt;![endif]--&gt;</span>
<span class="c">&lt;!--[if IE 8 ]&gt;
&lt;html lang="en" dir="ltr" class="ie ie8"&gt;
&lt;![endif]--&gt;</span>
<span class="c">&lt;!--[if IE 9 ]&gt;
&lt;html lang="en" dir="ltr" class="ie ie9"&gt;
&lt;![endif]--&gt;</span>
<span class="c">&lt;!--[if gt IE 9]&gt;
&lt;html lang="en" dir="ltr" class="ie"&gt;
&lt;![endif]--&gt;</span>
<span class="c">&lt;!--[if !IE]&gt;&lt;!--&gt;</span>
<span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">"en"</span> <span class="na">dir=</span><span class="s">"ltr"</span><span class="nt">&gt;</span>
<span class="c">&lt;!--&lt;![endif]--&gt;</span></code></pre></figure>


<p>Quite clearly this gets ever uglier, but the solution is entirely encompassed in the structural layer; we will always have the correct class, even if CSS or JavaScript are unavailable for some reason. We also have the same markup regardless of user-agent string, which means caching is not a problem.</p>

<p>The only flaw with this solution is that we can only target versions of Internet Explorer. No other browser implements conditional comments.</p>

<h3 id="use_css_properly_and_make_use_of_the_cascade">Use CSS properly and make use of the cascade</h3>

<p>As previously stated, CSS is designed to cascade. This means the built-in error handling will ignore properties the interpreter does not understand, and we can override rules based on specificity and source order. In most cases, these key features are more than adequate to develop gracefully degrading stylesheets.</p>

<p>Most capable front end developers are already doing this and coping just fine. Add this to the previous IE targeting approach and you’ll find that you do not need to over-engineer a solution.</p>

<h2 id="in_summary">In summary</h2>

<p>So, in summary then, I absolutely cannot recommend implementing Modernizr as a best practice for front end development. It attempts to solve a problem from the wrong direction, and introduces a new potential point of failure. What’s more it breaks the fundamental ethic of web standards; the separation of concerns.</p>

<p>I continue to recommend well crafted, gracefully degrading CSS, backed up by conditional commented classes on the <code>html</code> element for targeting IE.</p>

<p>Modernizr may still be a worthy solution for JavaScript-only feature sniffing, if only it allowed the developer to disable the injection of classes on the <code>html</code> element.</p>
</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[SEO for Web Developers: Page Construction]]></title>
        <link href="https://nefariousdesigns.co.uk/seo-for-web-developers-page-construction.html"/>
        <updated>2011-04-06T17:29:27+08:00</updated>
        <id>https://nefariousdesigns.co.uk/seo-for-web-developers-page-construction</id>
        <content type="html"><![CDATA[<p>Following on from “<a href="http://nefariousdesigns.co.uk/archive/2011/03/seo-for-web-developers-keywords-and-links/">SEO for Web Developers: Keywords and Links</a>”, this next article in my SEO series focuses on page construction. Whilst I’ve previously stated that in-links (i.e. external incoming links) are the fundamental workhorse of good SEO, it is also important to make sure you are constructing your pages in a way that easily exposes your content, and that clearly links it to your identified keywords.</p>

<p>Further to that, it’s important to know what the search bots are looking for when they spider your pages. From URL structure through to semantic markup and page specific metadata, there are a multitude of features you can build-in from the start that will improve the search engines’ insight into your content.</p>

<!--more-->

<h2 id="a_note_on_ranking_factors">A note on ranking factors</h2>

<p>Every two years, <a href="http://www.seomoz.org/">SEOmoz</a> conduct a survey across various SEO experts which they use to publish <a href="http://www.seomoz.org/article/search-ranking-factors">statistical findings in relation to search engine rankings</a>. This data is exceptionally useful in judging what elements to concentrate your efforts on during development.</p>

<p>In 2009 link metrics were worth a whopping 43% of value when calculating rankings. However, in the latest figures, that value has dropped to only 22%, which brings it in line with similar values for domain-level link authority (i.e. your domain is a “trusted” domain for quality). This reduction in size hasn’t resulted in other factors growing in value, but rather new factors have been introduced. These additions are domain-level keyword usage (how the keywords are relevant across the site), domain-level brand metrics (highlighting the importance of “brands” as a whole), and page-level traffic/query metrics.</p>

<h2 id="understanding_the_bots">Understanding the bots</h2>

<p>Understanding how the search engine bots evaluate your pages and content is key to learning how page construction affects SEO.</p>

<h3 id="page_vs_site">Page vs Site</h3>

<p>I have previously written—in my article “<a href="http://nefariousdesigns.co.uk/archive/2007/03/semantics-and-structure/">Semantics and Structure</a>“—of the importance of remembering that the web is simply a network of single pages. This network has only a vague understanding of the <em>human</em> concept of site; via the comprehension of URLs beneath a fixed domain—and even that doesn’t necessarily translate to a single site, despite being used for authority rankings. Large sections of search bot AI has been dedicated to discerning site structure from the links within your pages.</p>

<p>Whilst we can see from the metrics above that domain-level factors are now more prevalent in the calculations for ranking, it is still important to imagine each page of your site as an independent unit, and structure your content and code accordingly. This means that the <em>page</em> title should be situated in an <code>h1</code> tag and <em>not</em> the site title. That is unless you’re developing the home page, in which case the site title probably <em>does</em> belong in an <code>h1</code> element.</p>

<p>Site-wide architecture should be situated within non-pertinent markup (i.e. markup that doesn’t apply any semantic emphasis on the content) and placed accordingly in the source order. I've heard very peculiar things about content placed in paragraph tags being more pertinent than content that isn’t. In my experience this is a significant fallacy. For more information about “pertinent markup”, read the “<a href="#on_page_optimisation">On-page optimisation</a>” section later in this article.</p>

<h3 id="block_level_analysis">Block-level analysis</h3>

<p>Search engines, for the most part, follow an algorithm of block-level analysis. This means they will break a page down into sections (e.g. masthead, navigation, footer, main content, secondary content etc.) as a signal towards ranking the content within.</p>

<p>It is a good idea to make sure that the content you want to rank for is situated within your main content area. This may sound obvious but in a brave new world of modular development, and pages made up of “modules” of content, it is surprisingly easy to confuse the search engines and suffer for it in the rankings.</p>

<h3 id="source_order_is_important">Source order is important!</h3>

<p>It’s also important that you are prioritising your main content in your source order. Search engines will only evaluate the link text of the first use of a URI in a page. If you’re repeating a link with more valuable and relevant link text in your content than you are in your navigation, you’ll need to make sure the navigation comes <em>after</em> the main content. This is often the exact opposite of good UI design which will attempt to <a href="http://www.websiteoptimization.com/speed/tweak/clickstream/">place navigation in the most obvious place; across the top, or down the left</a>.</p>

<p>Take the following code as an example:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/about/"</span><span class="nt">&gt;</span>About me<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/"</span><span class="nt">&gt;</span>Blog<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/contact/"</span><span class="nt">&gt;</span>Contact<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>

<span class="nt">&lt;h1&gt;</span>My site<span class="nt">&lt;/h1&gt;</span>

<span class="nt">&lt;p&gt;</span>Welcome to my site. In here you can find
<span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"/about/"</span><span class="nt">&gt;</span>information about me and
my career<span class="nt">&lt;/a&gt;</span> and <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"/blog/"</span><span class="nt">&gt;</span>my personal
blog about web development and the
internet<span class="nt">&lt;/a&gt;</span>.<span class="nt">&lt;/p&gt;</span></code></pre></figure>

<p>Here the navigation links will be the first things evaluated by the bots, but they’re probably not the most contextually relevant links to the content in question. In fact, the second set of links include good keywords and may add significant value. For this reason the better option would be this:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;h1&gt;</span>My site<span class="nt">&lt;/h1&gt;</span>

<span class="nt">&lt;p&gt;</span>Welcome to my site. In here you can find
<span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"/about/"</span><span class="nt">&gt;</span>information about me and
my career<span class="nt">&lt;/a&gt;</span> and <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"/blog/"</span><span class="nt">&gt;</span>my personal
blog about web development and the
internet<span class="nt">&lt;/a&gt;</span>.<span class="nt">&lt;/p&gt;</span>

<span class="nt">&lt;ul&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/about/"</span><span class="nt">&gt;</span>About me<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/blog/"</span><span class="nt">&gt;</span>Blog<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">"/contact/"</span><span class="nt">&gt;</span>Contact<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>Obviously you can change the <em>visual</em> position of this content with CSS. Whilst the more sophisticated search bots will render CSS in an attempt to detect invisible content (i.e. that which is hidden either through <code>display</code> or <code>visibility</code> rules, or that which is moved offscreen), they are less bothered about the reordering of content visually.</p>

<h2 id="creating_content">Creating content</h2>

<p>It may sound entirely obvious but it’s exceptionally important to write good textual content for search engines. You will always rank higher if you include a good balance of text and links—with a high relevancy to each other—on your pages.</p>

<h3 id="duplication_is_bad">Duplication is bad</h3>

<p>Try to avoid duplication of content. By this I mean avoiding the same content on two different URIs. If your content <em>is</em> duplicated then you will be diluting its value by placing it in two places, even if it’s actually the same page served from two different URIs. I’ll cover the method you should use to declare the One True Version™ of your pages later on.</p>

<p>It’s also important to make sure your pages don’t duplicate content that is elsewhere on the internet. Good examples of this sort of repetition would be travel brochure text or product descriptions which are highly likely to be used on a multitude of affiliate sites; especially if that content is included in some sort of feed. Wherever possible try and create your own content; it will always serve you better and will ultimately separate you from the crowd.</p>

<h3 id="dynamic_vs_static_content">Dynamic vs. static content</h3>

<p>Dynamic content is that which updates regularly and hardly ever stays the same from day to day. Good examples of this might be a list of blog posts on a blog index page (where the blog items update regularly), news item indexes, feeds from other sites (e.g. RSS, Twitter etc.), and regularly moderated lists of links.</p>

<p>Static content is that which hardly ever changes. Good examples might be “about me” text on your blog, the description on a product detail page, and the article text on a blog article page.</p>

<p>It is very important to find the right balance of both dynamic and static content on your pages. Some pages will suit more static content (e.g. the article page of a blog) whereas others will suit more dynamic content (e.g. the index of that blog). In either case, make sure you’re including some of <em>both</em> types of content. On the article include links to the top articles on the blog, or feeds from Delicious or Twitter; on the index page include some static “about this blog/author” text.</p>

<h2 id="design_your_uris">Design your URIs</h2>

<p>Since links are the most important part of your SEO strategy, it’s hardly surprising that the <em>design</em> of the URI is a fundamental ranking factor. It’s important that you use just as much care with the URI as you do with the text of those links. Here are the important factors in good SEO-friendly URI design:</p>

<h3 id="keywords_in_your_domain">Keywords in your domain</h3>

<p>If you can, try to get some keywords in your domain. Often the most successful domains will have one or more relevant keywords in their domain name, and the closer to the left the better. A good example of this might be something like travelsupermarket.com, which is currently number one in Google for “travel”.</p>

<p>Rather interestingly, _exact_ keyword match domains seem to perform marginally better than domains with _some_ keywords. By this I mean domains that are entirely formed of keywords in the order for which they are searched (e.g. cheapmajorcaholidays.com). Hyphenated exact match domains (e.g. cheap-majorca-holidays.com) seem to perform slightly worse than those without hyphens, and domains that contain all query terms but are not an <em>exact</em> match are marginally worse again.</p>

<h3 id="choose_the_right_tld">Choose the right TLD</h3>

<p>Rather notably the .com TLD (top-level domain) appears to perform better than any other TLD. That’s not to say that you can’t easily out rank a .com domain, but they do seem to gain an advantage in a like-for-like ranking test with pretty much every other TLD I tried.</p>

<h3 id="subdomains">Subdomains</h3>

<p>Subdomains do not count as part of the domain. Cross subdomain links, as previously stated, are deemed internal and URIs containing a keyword subdomain appear to rank similarly to URIs with the same keyword as the first path element. Example:</p>

<pre><code>http://games.mygamessite.com/
</code></pre>

<p>Ranks the same as:</p>

<pre><code>http://mygamessite.com/games/
</code></pre>

<h3 id="keep_paths_shallow">Keep paths shallow</h3>

<p>Try to keep your URI path to a minimum. Each level you go down the hierarchy, the less value you give to keywords within it. This is another good reason to maintain a <a href="http://nefariousdesigns.co.uk/archive/2011/03/seo-for-web-developers-keywords-and-links/#improving_8220crawlability8221">flat site architecture</a>. Also, remember that the keywords on the left of each path segment (i.e. each section delimited with /) are the ones with the highest value at that level.</p>

<p>The maximum number of layers (or segments) you should use in a path is about 3. Any more than that and you’ve basically lost any SEO benefit from that section of the URI.</p>

<h3 id="be_strict_with_your_characters">Be strict with your characters</h3>

<p>There are a limited subset of characters that are permissible in URI syntax. However, that subset still allows a great variation in the <em>style</em> of your characters. In general it is best to keep your URIs strictly lowercase so as to cut down on the chance of creating or generating duplicates through case sensitivity. Also, try and internationalise the character set in your URIs; it’s always going to be easier to match a UTF-8 search term against a UTF-8 keyword in your URI.</p>

<h3 id="space_separators">Space separators</h3>

<p>There are several characters that can be decoded as a space in URI syntax, but only two that will work successfully as part of your path: “%20”, and “-“. It is best to enforce the use of a hyphen as a word separator in your paths. Google understands this as a space, and it will ensure your URIs remain readable. Underscores (“_”) are not recognised as a word separator and are therefore of little use. <a href="http://www.mattcutts.com/blog/dashes-vs-underscores/">Matt Cutts has previously discussed this in his "dashes vs. underscores" blog post</a>.</p>

<h3 id="branches_and_leaves">Branches and leaves</h3>

<p>Do not underestimate the value of human readability when designing your URIs. I have personally experienced, through extensive user research and user testing, that users afford a certain level of confidence to a readable URI. What’s more, some SEO consultants whom I have spoken with recommend applying slightly different rules to branch and leaf URIs.</p>

<p>A branch URI is a node that could potentially lead to more branch URIs or leaf URIs. The recommendation is that these URIs should end with a /.</p>

<pre><code>Branches:

http://sportsnews.com/football/
http://sportsnews.com/football/bundesliga/
</code></pre>

<p>A leaf URI is one that is the final node in the path tree. The recommendation is that these URIs should <em>not</em> end with a /, and should include some kind of filetype extension (usually <code>.html</code>). I prefer leaving out the extension myself, since it feels a bit old school and almost enforces a file-type assumption on the resource in question, but I accept I may be clouded by a developer’s understanding of HTTP and REST.</p>

<pre><code>Leaves:

http://sportsnews.com/football/international/teams/england.html
http://sportsnews.com/contact-us.html
http://sportsnews.com/terms-and-conditions
</code></pre>

<p>These recommendations amount to a more traditional OS directory-style vision, which makes them more familiar to the general non-techie user. It’s worth remembering that the URI is displayed prominently in the SERPs and as such inform the users’ confidence in clicking the item.</p>

<h2 id="on_page_optimisation">On-page optimisation</h2>

<p>Now you’ve hosted the pages on good SEO friendly URIs, and you’ve built a good network of links to those pages, it’s about time we looked at improving the way the search bots spider and evaluate your content:</p>

<h3 id="page_title">Page title</h3>

<p>The page title should sum up the content in as few words as possible. On left-to-right reading pages the left most words are deemed more significant (I’ve no research on right-to-left languages, but one would assume the opposite). A good title will have a healthy sprinkling of keywords whilst remaining human readable:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;title&gt;</span>SEO for Web Developers - Nefarious Designs<span class="nt">&lt;/title&gt;</span></code></pre></figure>

<p>Note that, in my titles, I’ve chosen to include the site title following the page title. Firstly, this means the site title will be included in the page title on the SERP, but it <em>also</em> means that the site title is associated as a keyword or keywords.</p>

<h3 id="semantic_content_mark_up">Semantic content markup</h3>

<p>The majority of semantic markup won’t give you a significant boost in rankings. Sorry folks, it’s true; despite the fact that we web devs love some good semantic markup, the search bots are less bothered. Let’s face it, the internet is still full of badly constructed web pages and the bots have to spider, analyse, and rank those too.</p>

<p>However there are <em>some</em> semantic elements (and some presentational elements) that will have a greater influence on denoting keywords in your content to the search engines. These are:</p>

<ul>
<li><p><code>h1</code>-<code>h6</code>: Well structured headings, that are relevant to your content (and not used as way-finders such as “navigation”) are highly important. The <code>h1</code> on your page is arguably the second most important element short of your page <code>title</code> and should contain relevant keywords accordingly.</p></li>
<li><p><code>em</code>, <code>strong</code>, <code>i</code>, <code>b</code>: Emphasising textual content with these tags will infer the content has some degree of added value. However, it’s important not to saturate your content with this as it will inevitably be flagged as keyword spam. Overall my tests were inconclusive in quantifying the effect of emphasised keywords, but there is clearly value in it.</p></li>
<li><p><code>a</code>: I’ve previously waxed lyrical on the importance of links within your content, and the textual content of those links is just as important. Linking to similar pages with text that involves your keywords, or is simply related, can significantly boost your pages’ performance in the SERPs.</p>

<p>As a side note, I’ve been told by so-called SEO “consultants” that all internal links should be fully qualified (i.e. be absolute links including the domain) to prevent scrapers from duplicating your content elsewhere on the internet. This is absolute nonsense. There’s really no reason that a scraper won’t be able to remove the domain from any links it identifies as internal to your site (i.e. on the same domain as the page it’s scraping).</p></li>
</ul>

<h3 id="meta_elements">Meta elements</h3>

<p>There are plenty of articles misrepresenting the value of <code>meta</code> elements in terms of SEO. For pretty much the last ten years, they have been mostly irrelevant for SEO. In fact, at the moment, this very site isn’t using them (more through laziness than intention—the site templates are old and I intend on migrating away from them sooner or later).</p>

<h4 id="keywords">Keywords</h4>

<p>The keywords <code>meta</code> element is all but abandoned by todays’ search engines. You will see little effect in rankings if you remove it altogether. I have noticed some smaller search engines using it, and it’s conceivable that other search engines may use links from these search engines as authority on your content. In short, you might see a small amount of benefit by proxy, but possibly not enough to warrant making the effort to keep the keywords list up to date and matching your content.</p>

<h4 id="description">Description</h4>

<p>The description <code>meta</code> element is used as the first port of call for the description of your page in the search engine. There is also a minor ranking effect from including keywords in this description but as ever, it’s important not to spam them here.</p>

<h3 id="link_element">Link element</h3>

<p>The <code>link</code> element is a sneaky little devil. Most web developers use it solely for linking stylesheets to their pages, but it has so many other uses that can help the search engines understand your site architecture better.</p>

<p><a href="http://www.w3.org/TR/html401/struct/links.html#h-12.3">The <code>link</code> element</a> allows you to specify another URI that is linked to your page, and also what relationship that URI has with the current one. To specify the relationship, you declare it in the <code>rel</code> attribute. The <code>rel</code> attribute has many possible values, but only a few that are relevant to SEO:</p>

<h4 id="canonical">Canonical</h4>

<p>At a minimum it’s important to understand the canonical <code>link</code> element. This allows you to declare the One True Version™ of any page on your site. This is probably easier to explain through example. Consider the following two URIs:</p>

<pre><code>http://sportsnews.com/football/

http://sportsnews.com/football/?ads=false
</code></pre>

<p>Assuming these are actually the same page, the search engine will consider these to be unique URIs and could penalise you for duplication of your content. To avoid this, it’s important to declare one version as the canonical version. To do this you add the following to the page:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">"canonical"</span> <span class="na">href=</span><span class="s">"http://sportsnews.com/football/"</span><span class="nt">&gt;</span></code></pre></figure>

<p>This method is also true of something more subtle like “topic” style pages. Imagine the following URIs:</p>

<pre><code>http://sportsnews.com/teams/tottenham-hotspur/peter-crouch

http://sportsnews.com/teams/england/peter-crouch
</code></pre>

<p>By adding a canonical <code>link</code> to the first item we can declare that, although the pages are exactly the same, the second is actually the same page on a slightly different URI.</p>

<h4 id="others">Others</h4>

<p>There are a whole host of available options to use in the <code>rel</code> attribute of the <code>link</code> element that may improve the search engines’ understanding of your pages and site structure. I really can be bothered listing them all out here, but you can find <a href="http://www.seoconsultants.com/meta-tags/link-relationship">an interesting explanation of SEO relevant <code>rel</code> values here</a>.</p>

<h2 id="search_bots_as_knowledge_based_systems">Search bots as knowledge-based systems</h2>

<p>Modern search engine bots are incredibly complex programs. Considering the amount of information they gather on each pass of your pages, they should certainly be considered to be knowledge-based systems. As the web changes, so do the methods the bots adopt to navigate your pages in as close to a humanised way as possible.</p>

<p>To this end, both Googlebot and Bingbot are capable of understanding fairly complex navigation systems. What’s more, they are very good at evaluating navigation links within your pages to ascertain different routes to your content. Through this understanding they are able to apply value calculations to specific URIs.</p>

<h3 id="breadcrumbs">Breadcrumbs</h3>

<p>Google announced at the end of 2009 that they were attempting to display site hierarchies as an alternative to the URL in the SERPs where they could surmise it from on-page breadcrumbs. For more information on this, see “<a href="http://googleblog.blogspot.com/2009/11/new-site-hierarchies-display-in-search.html">New site hierarchies display in search</a>” on the Googleblog.</p>

<p>To do this, Googlebot simply analyses any constructs that look like a breadcrumb within your pages. This can be either a list of links identified by “breadcrumb” as an ID or class, or a set of links separated by the “&gt;” character. In my tests both of these methods have been successfully picked up by Googlebot and displayed as site hierarchies on the Google SERP.</p>

<p>There are other methods of marking up breadcrumbs using “rich snippets” which I will talk about later.</p>

<h3 id="learning_new_interaction_paradigms">Learning new interaction paradigms</h3>

<p>Googlebot has been designed to understand modern in-page navigation paradigms, such as tab, carousel, and accordion widgets. It does this by searching for the presence of known markup configurations and included scripts.</p>

<p>For this reason, it’s sometimes better to use commonly used scripts such as popular jQuery or jQuery UI widgets which are likely to have a large user base across the web. Sadly this often means that badly written front-end interaction scripts may perform better than more bespoke options.</p>

<p>You can also improve Googlebot’s understanding of your pages by adopting common element identifiers on your JavaScript enhanced elements. This means using classnames such as “open”, “closed”, “active”, or “selected” etc.</p>

<p>It is worth noting, however, that in my tests rankings seemed better when pages used prebuilt widgets (i.e. those already in its knowledge base) than with bespoke techniques using predictable classes or IDs.</p>

<h3 id="rich_snippets">Rich snippets</h3>

<p>These days Google is capable of rendering a large number of “rich snippets”. These are generally pieces of code specifically designed for marking-up data of a particular type, e.g. <a href="http://microformats.org">microformats</a>, <a href="http://dev.w3.org/html5/md/">microdata</a>, and <a href="http://rdfa.info/">RDFa</a>. Often these snippets simply involve a range of predictable element identifiers or tags.</p>

<p>When displaying search results, Google will try and handle these rich snippets in the best way it sees fit. For example, reviews will appear as a 5 star rating widget just below the title of the search item. Recipes, on the other hand, are awarded their very own search utility:</p>

<p><a href="http://www.google.com/search?q=chicken+madras&amp;tbs=rcp%3A1">Google Recipe search for “Chicken Madras”</a></p>

<p>Currently, Google supports the following types of rich snippet:</p>

<ul>
<li>Reviews</li>
<li>People</li>
<li>Products</li>
<li>Businesses and organisations</li>
<li>Recipes</li>
<li>Events</li>
</ul>

<p>For more information on implementing these snippets for your content, take a look at <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=99170">Google’s excellent rich snippet explanation page</a>.</p>

<h2 id="javascript">JavaScript</h2>

<p>Googlebot currently runs a headless browser as it navigates pages. A headless browser is basically a browser with no user interface and, in this context, it means Googlebot constructs the correct DOM, and attempts to render all CSS and some JavaScript. It also means that many DOM events are fired as it follows links through your site, potentially exposing functionality it wouldn’t normally find.</p>

<p>The JavaScript related tests I have run to analyse the bots’ paths through my sites have largely been quite inconclusive; it appears that sometimes Googlebot simply evaluates embedded script in the page (i.e. code inside <code><script></code> tags) for URLs and then spiders those, and other times it is finding URLs within external script files (i.e. that which is included using <code><script src=“”></script></code>). It also appears to find URLs manipulated into links on click events. However, it is definitely finding links in embedded script tags more regularly than those in external script files.</p>

<p>So far I haven’t managed to get Googlebot to spider content or links added during a DOMready or window.onload event. My tests are ongoing and I shall endeavour to document my findings on this blog once I have a clearer picture.</p>

<h2 id="summary">Summary</h2>

<p>Apologies for the length of this article, it just kept growing! There was so much to cover that I really didn’t want to have to split it out into several sub-articles; especially considering the fact that it’s already part of a series.</p>

<p>Hopefully you’ve now got a head-start when it comes to building your pages for SEO. Tie this to the link building and keyword targeting you’ve been doing following my first article and you’ll be ranking well in the SERPs.</p>

<p>In the following article I’ll be looking at what you can do to help the search engine robots specifically by providing metadata for them, and how proper handling of HTTP can improve crawlability. I’ll also cover some basic tools that can aid your monitoring and improvement of SEO.</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[SEO for Web Developers: Keywords and Links]]></title>
        <link href="https://nefariousdesigns.co.uk/seo-for-web-developers-keywords-and-links.html"/>
        <updated>2011-03-23T06:47:12+08:00</updated>
        <id>https://nefariousdesigns.co.uk/seo-for-web-developers-keywords-and-links</id>
        <content type="html"><![CDATA[<p>Since the dawn of the web, developers and content editors have sought insight and enlightenment into the arcane art of search engine optimisation (SEO). This relentless battle to rise above the competition and feature at the top of the search engine result page (SERP), for a chosen keyword or search term, has forced a constant clandestine evolution upon the search engines themselves whilst they adapt to out-trick the trickster.</p>

<p>What’s more the proliferation of false knowledge, the equally charlatan-populated worlds of SEO consultancy and web development, and the sheer abundance of SEO false positives have meant that snippets of true SEO wisdom are drowning in a sea of irrelevant balderdash.</p>

<p>It is no wonder then that your average web developer is not armed with the erudition required to fight the good fight; knowledge that will allow them to articulate the message of their content to the search engines and therefore be exposed to a wider audience.</p>

<p>Fear ye not, weary web devs, for here is your codex of power. I hereby commit to blog my personal experiences and knowledge of Getting SEO To Actually Work™. Everything I discuss in this series of articles has been learned through experimentation, careful analysis, and search-bot honey-pot test sites. Oh, and mummyfrakkin’ science, bitches.</p>

<!--more-->

<h2 id="keywords">Keywords</h2>

<p>One term you will hear more than others when researching or improving SEO is “keyword”.</p>

<p>A keyword is a word or phrase that contains high relevance to your content’s subject matter. A keyword is best imagined as a term a user might enter into a search engine in the hope of finding content like yours. For example, on a travel website generalised keywords might include “travel”, “vacation”, and  “holiday”, whereas more specific keywords might be “5 star holidays” or “Greek holidays”.</p>

<p>As the search engines crawl and index the content on your pages they keep track of those pages in keyword-based indices. Thus, rather than storing 25 billion web pages all in one database, the engines maintain a vast array of smaller databases, each centred on a particular keyword term or phrase. This denormalisation makes data retrieval much faster, reducing it to mere fractions of a second.</p>

<h3 id="use_of_keywords">Use of keywords</h3>

<p>The search engines analyse the embedded keywords within your content to ascertain their relevance to the subject matter. This means a good way to optimise your content is to make sure the keywords are situated in key content structures, such as URLs, page titles, headings, and areas of emphasis (<code>&lt;strong&gt;</code>, or <code>&lt;b&gt;</code>; your non-presentational mark-up bears little relevance here). I’ll cover this in more detail when I talk about on-page optimisation later in this series.</p>

<p>It is also of note that a generalised keyword—such as “car insurance”, for example—will have a broader use, and therefore considerably more competition in terms of rankings. Something more specific like “women’s small car insurance” will limit your competition but might not have such a large search density. There is a clear balance to be found in your market and it’s important to identify the keywords you wish to target for a given page as early as possible.</p>

<h3 id="a_word_on_keyword_density">A word on keyword density</h3>

<p>The term “keyword density” describes the density (i.e. occurrence) of a keyword within your content. The term is a veritable minefield of misinformation and should set off alarm bells as soon as it is mentioned.</p>

<p>The density of your keywords bears no relation to the quality, semantics, and relevancy of your content; and it is these characteristics that glean the highest return. Do not be tempted into thinking that a page saturated with keywords will perform better in search rankings than a page that seats fewer keywords in higher quality, higher relevancy content.</p>

<h3 id="keyword_targeting">Keyword targeting</h3>

<p>As I said earlier, it’s important to identify the keywords you wish to target before you do anything else. To be effective, SEO requires that keywords are associated with and contained in your content at as many levels as possible.</p>

<p>Most SEO consultancies will invest significant amounts of time researching keywords for a given market, and also the competition against those keywords. What’s more, that analysis is ongoing, as the value of your chosen keywords will fluctuate wildly due to changes in the market, target saturation (i.e. too many people using it), and other such external factors (including black-hat devaluation which I will cover later).</p>

<h2 id="links">Links</h2>

<p>Let’s make sure we’re not under any false illusions before we get too far in; the two most important things about any page—in terms of SEO—are the links into it, and the keywords associated with those links. You could serve up the most hideous pile of non-web-standards, non-semantic, tables-for-layout, text-in-images content, and if the links into it are plentiful, and also contain the right keywords and/or link juice (more on that later), it will perform well in the rankings. Links are how the search engines will begin to calculate the relevancy of your page. Once they have a relevancy rating, it will then be affected by the analysis of the <em>content</em> of that page.</p>

<p>That’s not to say that there isn’t some artistry in the placement, design, and variance of those links, but since hyperlinking is the very essence of the world wide web, it is unsurprising that it is also the very essence of SEO. A high quality link will be featured on a page containing high relevance to the link’s subject matter, will be situated in an area of highly relevant content, and will have link text containing relevant keywords. It’s all about relevance.</p>

<h3 id="link_juice_aka_pagerank">Link Juice (aka PageRank)</h3>

<p>Search engines apply a numeric score to a spidered page known as PageRank. This is often called “Link Juice” in SEO circles and is a calculated number based on the links—and the quality of those links—into, and out of, your page. This score is then used as a factor in calculating the ranking of your page against keyword relevancy.</p>

<p>As the search-bots spider the links within a page they pass a proportion of the host page’s score to each link. The page at the other end of the link is therefore afforded a total based on the score flowing into it from links elsewhere <em>and</em> how it passes that score onward. The best way of imagining this is as a complex network of pipes and sluice gates (links), with the score being the liquid within. High quality pages will have higher page rank due to incoming links with a higher score.</p>

<p>Bear in mind, however, that “link juice” is calculated differently based on “internal” and “external” links. Most search engines appear to deem links within a domain (internal) of less importance than those from a different domain entirely (external). For the most part, my linking tests seems to infer that cross-sub-domain links are <em>also</em> deemed internal. However that sort of testing is fairly difficult to quantify, so I’d recommend investigating for yourself if you’re intending doing something like that.</p>

<p>As an aside, it’s worth noting that a high link score (juice, PageRank, call it what you will) <em>does not</em> necessarily mean high SERP rank.</p>

<h3 id="the_8220nofollow8221_rel_attribute_value">The “<code>nofollow</code>” <code>rel</code> attribute value</h3>

<p>Following the dawn of the “blogosphere” and other such UGC (user-generated content), such as forums and guestbooks, there was an explosion of link-spam. These are links that have been placed on as many different sites as possible—either manually, or through automated processes known as spam-bots—with little relevance to the intended page content or conversation. This link spam is a black-hat method of rustling link juice into a given target page.</p>

<p>To combat this, the search engines implemented a scheme that allows a developer to mark a link as non-pertinent in the flow of link juice. To do this, you apply a <code>rel</code> attribute of <code>nofollow</code>:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"http://somewhere.com/"</span> <span class="na">rel=</span><span class="s">"nofollow"</span><span class="nt">&gt;</span>Link<span class="nt">&lt;/a&gt;</span></code></pre></figure>

<h4 id="nofollow_sculpting"><code>nofollow</code> sculpting</h4>

<p>The <code>rel="nofollow"</code> attribute used to allow you to <em>sculpt</em> the score that would pass between links on your site, by preventing score flowing through no-followed links. <strong>This is no longer the case</strong>.</p>

<p>Before Google changed their algorithm, <code>rel="nofollow"</code> used to be handled like this:</p>

<pre>Link 1 - Link score/4
Link 2 - Link score/4
Link 3 - Link score/4
Link 4 - Link score/4

Link 1 - Link score/3
Link 2 - No follow
Link 3 - Link score/3
Link 4 - Link score/3</pre>

<p>Now it works like this:</p>

<pre>Link 1 - Link score/4
Link 2 - No follow
Link 3 - Link score/4
Link 4 - Link score/4</pre>

<p>This means that you get significantly less benefit from no-following a link than you used to. However, all the search engines (with Ask being an exception) state that they do take <code>rel="nofollow"</code> into account when weighting rankings:</p>

<p>Google, Yahoo!, and Bing say no-followed links are treated as plain text and therefore have no added emphasis when calculating keyword relevancy. Y! and Bing, however, <em>do</em> state that they use no-followed links for discovery and may follow them without affecting your rankings.</p>

<p>It’s all very complicated but suffice to say, it’s probably better to mark unimportant links on your pages as <code>rel="nofollow"</code> and let the search engines sort out amongst themselves what they want to do with it.</p>

<h2 id="improving_8220crawlability8221">Improving “crawlability”</h2>

<p>To improve the efficiency of spidering (i.e. how the search bots crawl your site) it is advisable to maintain a flat site architecture. In this context, site architecture is simply a means to describe the link depth of your pages. “Link depth” is the number of links it takes to navigate from the home page of your site to any given page within it. The shorter the maximum link depth, the better the “crawlability”.</p>

<p>For the most part, search engines understand a “site” to be a confined <a href="http://en.wikipedia.org/wiki/Graph_(data_structure)">graph</a> of internal links as mapped by the search bot when it spiders your site. Each pass through the site will give the bot a better understanding of your site-map. There are several ways to inform this process, such as sitemap XML files and the robots.txt file. I’ll cover those later in this series.</p>

<h3 id="maximum_links_per_page">Maximum links per page</h3>

<p>Most search engines recommend hosting less than 100 links on any page. This is primarily because, above a certain number, link score will deteriorate due to a search engine defined degenerative quality equation. This will result eventually in links that are not spidered at all. Secondly, a large number of links on any page is a signal of diminished content quality and will directly affect SERP rankings as a result.</p>

<p>The arbitrary value of 100 is misleading though as a high quality landing page, such as your homepage, can easily maintain 250-300 good quality links without penalty. The pages at the next level can then host ~200 quality links and so on. With this architecture, a site with a link depth of 4 or 5 can easily maintain millions of pages within its structure with little or no penalty.</p>

<h2 id="link_building">Link building</h2>

<p>Link building is the art of obtaining external links back to your content from high quality (i.e. high relevance to your content subject matter) pages elsewhere on the web. There is a fine line to walk between link building and creating link spam; it is the difference between the relevance of the surrounding content on the link hosting page.</p>

<p>Many SEO companies employ link building specialists who will inundate the web with links, either posted manually or accrued through link sharing contracts, registration with pay-to-link directories, and other such socially manufactured solutions.</p>

<h3 id="third_party_linking">Third-party linking</h3>

<p>To build effective links it also a good idea to offset the effort. In some cases, placing a link on a site with high traffic, but that isn’t particularly high quality—or isn’t even spidered effectively—can work in your favour. A good example of this is Facebook which hides a large majority of its content from search engine spiders. A link placed on Facebook has a high likelihood of being reposted elsewhere, where the link quality will be vastly improved.</p>

<p>In today’s internet company you will find many Social Media “Experts” who’s sole responsibility is to use social networking to market the brand, the company, and, more importantly, links to the website. Whilst the quality of links on social networks is debatable, the benefit of reposts elsewhere cannot be ignored, regardless of quality.</p>

<h3 id="link_bait">Link bait</h3>

<p>Another technique when link building is to create content that can be classed as “link bait”. This is content that has a high likelihood of being reposted elsewhere and is therefore subject to significant third-party linking.</p>

<p>In my personal opinion the concept of link bait is very hypothetical; one man’s link bait is another man’s quality content. In web development particularly there are any number of cynical parties waiting in the wings to troll a link as link bait. This may, however, have something to do with the inherent cynicism in the development world in general.</p>

<h2 id="summary">Summary</h2>

<p>Understanding the concept of keywords, and then applying that concept to link building and your internal link structure, are really the two base concepts of SEO. Once you have mastered them you should be well on the way to improving your performance in search engine rankings.</p>

<p>The next article in this series will cover SEO in page construction, including information about on-page optimisation, designing your URLs, correct use of HTTP, and other such technical information.</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Stalking friends on GitHub]]></title>
        <link href="https://nefariousdesigns.co.uk/stalking-friends-on-github.html"/>
        <updated>2011-02-21T07:42:26+08:00</updated>
        <id>https://nefariousdesigns.co.uk/stalking-friends-on-github</id>
        <content type="html"><![CDATA[<p>A while back, I used <a href="http://pipes.yahoo.com/">Yahoo! Pipes</a> to filter my private <a href="https://github.com/">GitHub</a> RSS feed, so that it only shows information that may be interesting for me to track. The resultant feed allows me to see what my friends have started watching or have forked, or repos they have recently created, from the comfort of my feed reader.</p>

<p>Following a small refactor—guided by some more Pipes-knowledgable friends of mine (cheers <a href="http://blog.zottmann.org/">Carlo</a> and <a href="http://ginader.com">Dirk</a>)—I privatised my token, and allowed customisation of the GitHub account used.</p>

<p>So, without further ado, here’s the pipe; feel free to use it to stalk your friends on GitHub:</p>

<p><a href="http://pipes.yahoo.com/pipes/pipe.info?_id=85709214354b9319d6e345be3c1a6c46">GitHub Friend Stalker</a></p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[On coding standards]]></title>
        <link href="https://nefariousdesigns.co.uk/on-coding-standards.html"/>
        <updated>2011-02-01T06:00:16+08:00</updated>
        <id>https://nefariousdesigns.co.uk/on-coding-standards</id>
        <content type="html"><![CDATA[<p>In my time as a web developer, I have been involved in the definition, implementation, and maintenance of several different coding standards, across various web-based languages. In my experience, this process is not as straightforward as it first seems, and can lead to a great deal of headaches if not handled in a very specific manner.</p>

<p>As the front-end development team where I currently work are going through a definition process, I have been reminded of a few things I’ve learnt over the course of my career. With that in mind, I thought I’d type up some of that knowledge in the hope that it might benefit other developers out there.</p>

<!--more-->

<h2 id="some_things_to_remember">Some things to remember</h2>

<p>It’s important to remember that a developer takes great pride in his or her work, and as a result has a significant emotional attachment to the code they output. When that code is submitted for a code review—where the implementation of any coding standards is going to be assessed by the developer’s peers (obviously alongside other things)—it is important not to tear the code apart without respecting that emotional attachment.</p>

<p>Further to this, it is important that the reasoning behind the rules in the coding standard are rigorously explained and well documented, along with good and bad examples. If the developers understand <em>why</em> they should be doing something, you’re more likely to get them doing it as second nature.</p>

<p>Finally, always check to see if there is a more general coding standard you can utilise, such as <a href="http://www.python.org/dev/peps/pep-0008/">Python’s PEP-8 standard</a> or the <a href="http://pear.php.net/manual/en/standards.php">PHP PEAR standard</a>. It makes far more sense to start with one of these and then build your own standards upon it.</p>

<h2 id="why_have_a_coding_standard">Why have a coding standard?</h2>

<p>There is really only one reason to adopt a coding standard; to maintain a predictable base of easily maintainable, understandable, and legible code. Ultimately, you are aiming to develop code that can be picked up by any developer—either in an internal team, or some other, wider community—and easily read, understood, and either fixed or appended.</p>

<p>Further to that, it is not the opportunity to enforce your own particular coding style on others; in fact, you should probably expect to change your own style as there will invariably be some decisions made that will alter your usual syntax or method. This should be embraced as a <em>good</em> thing, as you may learn something.</p>

<h2 id="creating">Creating</h2>

<p>When creating a new coding standard, it’s important not to dictate rules to the wider team or community. The best standards are defined in agreement, not by dictation. It’s important to make the definition of <em>team</em> standards a <em>team</em> task.</p>

<p>When a standard—and the reasoning <em>behind</em> that standard—are offered to the team, discussion will invariable ensue. That discussion needs to be controlled and constructive, without dragging on. Nobody wants to sit and listen to two or three developers arguing; sooner or later someone will need to step in and make a decision, despite potentially disagreeing (and therefore upsetting) multiple parties involved.</p>

<p>A good way to avoid massive discussion on mailing lists, or in team meetings, is to make sure your recommendation and acceptance processes are not too complex. As soon as you instigate a complicated system of recommendation, confirmation, voting etc. you will instantly regret it. Developers are adverse to change, and you are potentially changing the very fundamentals of their day to day work. You just can’t expect the process to be quick and painless unless you <em>enforce</em> quick and painless at every possible stage.</p>

<p>The absolute best way to implement and maintain a coding standard is based on the outcome of code reviews. These are the perfect forum for discussion of style and method, and a good follow-up on that discussion is to update the coding standard.</p>

<p>The last thing you should bear in mind when developing a coding standard is that it will usually work best if it’s fairly language agnostic. Similar rules should be applied universally across languages; if you break this rule, you’ll quickly find yourself in a heated discussion about some minutia of syntax that is entirely deconstructive. Having said that, there are always going to be particular features and conventions of a specific language that should be applied to aid legibility or maintenance.</p>

<h2 id="comments">Comments</h2>

<p>I hate badly commented code. I also hate writing comments. Ergo, I hate my own code.</p>

<h3 id="comment_as_you_go">Comment as you go</h3>

<p>Commenting code is usually way outside the modus operandi of most developers. If we feel a piece of code should be commented, we’ll go back and do it afterwards, which means we’ve automatically given ourselves a mind-numbingly dull job that will, without fail, fall by the wayside upon release. To comment effectively, it’s important to do it as you go, even if you find yourself changing the comments as you refactor your code.</p>

<h3 id="comment_sensibly">Comment sensibly</h3>

<p>Comments should be added in distinct blocks, rather than commenting every single line. It’s important to remember what is important in a block of code and explain that. You’re documenting it for maintenance, so at least afford the next developer a modicum of intelligence. Of course, if you come back to it 6 months down the line, that next developer could very well be you!</p>

<p>When I say “distinct blocks”, I mean functions, methods, objects, classes, event callbacks, blocks of CSS rules, and anything else that requires explanation e.g. particularly complicated or confusing sections of functionality that might not otherwise be entirely obvious. Also, be sure to include references to other sections / files that may be relevant.</p>

<h3 id="pick_your_audience">Pick your audience</h3>

<p>As I’ve said previously, comments are there for the code maintainer, so if you can hide them from the end user, you may as well do so. Comments should be added in the template language rather than the HTML; likewise, any other code generation should keep the comments in the generator not the generated file (unless it is specifically pertinent to do so). If you comment JavaScript and CSS, make sure the comments are removed as part of your build process/combo handler, alongside minification.</p>

<h3 id="commenting_standards">Commenting standards</h3>

<p>Commenting standards, such as JSDoc, are a good thing. You’re already trying to implement a coding standard, you might as well leverage [manager++] someone else’s.</p>

<h2 id="naming_conventions">Naming conventions</h2>

<p>Language constructs may allow you the freedom of your given language, but please adopt a little restraint. It’s important to make them readable and decipherable by the next developer along.</p>

<h3 id="style">Style</h3>

<p>Try and adopt a naming convention that suits the style of the language. Here are some examples:</p>

<ul>
<li><p>HTML and CSS — Use hyphenated lowercase IDs and classes:</p>


<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">"live-scores"</span> <span class="na">class=</span><span class="s">"tab-module"</span><span class="nt">&gt;</span>
    …
<span class="nt">&lt;/div&gt;</span></code></pre></figure>

</li>
<li><p>JavaScript — Use camelCase variable naming, with constructors in UpperCamelCase:</p>


<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">myVar</span> <span class="o">=</span> <span class="kc">true</span><span class="p">,</span>
    <span class="nx">myFunction</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
        <span class="c1">// Wicked awesome codez here.</span>
    <span class="p">},</span>
    <span class="nx">MyConstructor</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">id</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">this</span><span class="p">.</span><span class="nx">id</span> <span class="o">=</span> <span class="nx">id</span><span class="p">;</span>
    <span class="p">};</span></code></pre></figure>

</li>
<li><p>PHP, Python — Use lowercase with underscore separation, with UpperCamelCase for classes:</p>


<figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="nv">$dev_name</span> <span class="o">=</span> <span class="s2">"Timmah"</span><span class="p">;</span>


<span class="k">function</span> <span class="nf">get_foo</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">return</span> <span class="s2">"foo"</span><span class="p">;</span>
<span class="p">}</span>


<span class="kd">class</span> <span class="nc">SimpleClass</span> <span class="p">{</span>
    <span class="c1">// property declaration</span>
    <span class="k">public</span> <span class="nv">$var</span> <span class="o">=</span> <span class="s1">'a default value'</span><span class="p">;</span>
    <span class="c1">// method declaration</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">displayVar</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">var</span><span class="p">;</span>
        <span class="p">}</span>
<span class="p">}</span></code></pre></figure>

</li>
</ul>

<h3 id="grace">Grace</h3>

<p>It is important to keep names concise yet explanatory. There’s no need to write a variable name that’s fifty characters long, if you could do it in ten. Likewise, it’s important you aren’t just writing a nonsensical string of characters that ends up looking like some kind of demented <a href="http://en.wikipedia.org/wiki/Countdown_(game_show)#Conundrum">Countdown Conundrum</a>.</p>

<p>Bad:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">boolean_flag_for_portrait_view</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span></code></pre></figure>

<p>Also bad:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">bl_flg_pview</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span></code></pre></figure>

<p>Good:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">is_portrait</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span></code></pre></figure>

<h3 id="prefixing_suffixing_type">Prefixing / suffixing type</h3>

<p>Type prefixes and suffixes are a bad idea; loosely typed languages allow the developer the ability to change things up, so you’d better expect it once in a while. Further to that, any intelligent developer can work out what type a variable is if they absolutely have to, so why waste the characters?</p>

<p>Final note: If type prefixes and suffixes are a bad idea, <a href="http://en.wikipedia.org/wiki/Hungarian_notation">Hungarian notation</a> is a very <em>very</em> bad idea. Don’t go there. SRSLY.</p>

<h2 id="style">Style</h2>

<p>As I’ve stated previously, a coding standard is <em>not</em> a way for you to enforce your own coding style on others. Try and keep any such rules to a minimum.</p>

<h3 id="tabs_vs_spaces">Tabs vs. spaces</h3>

<p>One of the first conversations you’re going to have, when defining a coding standard, is whether you should be using tabs or soft-tabs (spaces) for indentation. In a modern development environment, this is irrelevant—even in languages where whitespace indentation is important, such as Python.</p>

<p>A developer should be able to set-up their IDE to use either tabs or spaces when indenting, thus they shouldn’t have to worry about it. The only thing that <em>is</em> important in this area is that it remains uniform in any given file. There is nothing worse than opening a file to find some things indented by 4 spaces, and others indented by 3 [deviants!].</p>

<h3 id="legibility">Legibility</h3>

<p>It’s important to write code that is legible; the more so, the better. To aid comprehension of blocks of code, it is useful to separate them with new lines.</p>

<p>It’s also important to try to keep lines of code to a reasonable length. Many developers and coding standards recommend a length of around 80 characters, with some even enforcing it. Python’s PEP-8 certainly falls under this heading. Personally, I’d prefer going over that length if the line remains legible; often breaking a line with carriage returns can have a negative effect on legibility.</p>

<p>Similarly, Lines that are too long are often difficult to read. If this is the case, then you must attempt to find the most legible form. Legibility is <em>always</em> the most important factor.</p>

<h3 id="whitespace">Whitespace</h3>

<p>Liberal use of whitespace in your syntax can mean the difference between readable and unreadable code. Having said that, <em>over</em> use of whitespace can be entirely detrimental. Like my previous notes on style, it is important to find a balance when wrapping parentheses, expressions, assignments, and other such code with whitespace:</p>

<p>Readable:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">myVar</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">foo</span><span class="dl">'</span><span class="p">;</span>

<span class="k">for</span> <span class="p">(</span> <span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="nx">j</span> <span class="o">=</span> <span class="nx">myArray</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">j</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span> <span class="p">)</span> <span class="p">{</span>
    <span class="err">…</span>
<span class="p">}</span></code></pre></figure>

<p>Less readable:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">myVar</span><span class="o">=</span><span class="dl">'</span><span class="s1">foo</span><span class="dl">'</span><span class="p">;</span>

<span class="k">for</span><span class="p">(</span><span class="kd">var</span> <span class="nx">i</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span><span class="nx">j</span><span class="o">=</span><span class="nx">myArray</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span><span class="nx">i</span><span class="o">&lt;</span><span class="nx">j</span><span class="p">;</span><span class="nx">i</span><span class="o">++</span><span class="p">){</span>
    <span class="err">…</span>
<span class="p">}</span></code></pre></figure>

<h2 id="accepted_standards">Accepted standards</h2>

<p>There are many accepted standards used across multiple languages. It is important to make sure you don’t break these with your coding standard, even if you don’t specifically declare them anywhere. Good examples might be:</p>

<ul>
<li><p>Use of i, j, k for simple iterators.</p>


<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="k">for</span> <span class="p">(</span> <span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="nx">j</span> <span class="o">=</span> <span class="nx">myArray</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">j</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span> <span class="p">)</span> <span class="p">{</span>
    <span class="err">…</span>
<span class="p">}</span></code></pre></figure>

</li>
<li><p>Use of _ to denote private members.</p>


<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">myConstructor</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">_private</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">something private</span><span class="dl">'</span><span class="p">;</span>
<span class="p">};</span></code></pre></figure>

</li>
<li><p>Use of UPPERCASE to denote constants.</p>


<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">VERSION</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">v1.1</span><span class="dl">'</span><span class="p">;</span></code></pre></figure>

</li>
</ul>

<h2 id="expressions">Expressions</h2>

<p>Expressions are often where the complex logic within your code can be found. As such, to aid assimilation, you may like to break them down to their constituent parts.</p>

<p>A complex expression:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="k">if</span> <span class="p">(</span> <span class="nx">myArray</span><span class="p">.</span><span class="nx">length</span> <span class="o">&lt;</span> <span class="mi">4</span> <span class="o">||</span> <span class="p">(</span> <span class="nx">myString</span><span class="p">.</span><span class="nx">length</span> <span class="o">&gt;</span> <span class="mi">2</span> <span class="o">&amp;&amp;</span> <span class="nx">myString</span> <span class="o">!==</span> <span class="dl">'</span><span class="s1">foobar</span><span class="dl">'</span> <span class="p">)</span> <span class="p">)</span> <span class="p">{</span>
    <span class="err">…</span>
<span class="p">}</span></code></pre></figure>

<p>Might become:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">isArrayShort</span> <span class="o">=</span> <span class="p">(</span> <span class="nx">myArray</span><span class="p">.</span><span class="nx">length</span> <span class="o">&lt;</span> <span class="mi">4</span> <span class="p">),</span>
    <span class="nx">isStringCorrectLength</span> <span class="o">=</span> <span class="p">(</span> <span class="nx">myString</span><span class="p">.</span><span class="nx">length</span> <span class="o">&gt;</span> <span class="mi">2</span> <span class="p">),</span>
    <span class="nx">isStringMatched</span> <span class="o">=</span> <span class="p">(</span> <span class="nx">myString</span> <span class="o">!==</span> <span class="dl">'</span><span class="s1">foobar</span><span class="dl">'</span> <span class="p">),</span>
    <span class="nx">hasCorrectString</span> <span class="o">=</span> <span class="p">(</span> <span class="nx">isStringCorrectLength</span> <span class="o">&amp;&amp;</span> <span class="nx">isStringMatched</span> <span class="p">),</span>
    <span class="nx">isPassed</span> <span class="o">=</span> <span class="p">(</span> <span class="nx">isArrayShort</span> <span class="o">||</span> <span class="nx">hasCorrectString</span> <span class="p">);</span>

<span class="k">if</span> <span class="p">(</span> <span class="nx">isPassed</span> <span class="p">)</span> <span class="p">{</span>
    <span class="err">…</span>
<span class="p">}</span></code></pre></figure>

<p>If we clean it up further:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">isArrayShort</span> <span class="o">=</span> <span class="nx">myArray</span><span class="p">.</span><span class="nx">length</span> <span class="o">&lt;</span> <span class="mi">4</span><span class="p">,</span>
    <span class="nx">isStringCorrectLength</span> <span class="o">=</span> <span class="nx">myString</span><span class="p">.</span><span class="nx">length</span> <span class="o">&gt;</span> <span class="mi">2</span><span class="p">,</span>
    <span class="nx">isStringMatched</span> <span class="o">=</span> <span class="nx">myString</span> <span class="o">!==</span> <span class="dl">'</span><span class="s1">foobar</span><span class="dl">'</span><span class="p">,</span>
    <span class="nx">hasCorrectString</span> <span class="o">=</span> <span class="nx">isStringCorrectLength</span>
                       <span class="o">&amp;&amp;</span> <span class="nx">isStringMatched</span><span class="p">,</span>
    <span class="nx">isPassed</span> <span class="o">=</span> <span class="nx">isArrayShort</span>
               <span class="o">||</span> <span class="nx">hasCorrectString</span><span class="p">;</span>

<span class="k">if</span> <span class="p">(</span> <span class="nx">isPassed</span> <span class="p">)</span> <span class="p">{</span>
    <span class="err">…</span>
<span class="p">}</span></code></pre></figure>

<p>Note the fact that I have broken the logical operators onto their own lines. This is another technique that can sometimes aid the readability of an expression, should it adopt multiple ANDs and ORs.</p>

<p>This last example may look more complex to begin with, but should a second developer read your original code, they will be left confused. The second example breaks the expression down into constituent boolean values to aid legibility.</p>

<p>Now imagine we have a similar example, but adopted using ternary notation:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">output</span> <span class="o">=</span> <span class="p">(</span> <span class="nx">myArray</span><span class="p">.</span><span class="nx">length</span> <span class="o">&lt;</span> <span class="mi">4</span> <span class="o">||</span> <span class="p">(</span> <span class="nx">myString</span><span class="p">.</span><span class="nx">length</span> <span class="o">&gt;</span> <span class="mi">2</span> <span class="o">&amp;&amp;</span><span class="p">;</span> <span class="nx">myString</span> <span class="o">!==</span> <span class="dl">'</span><span class="s1">foobar</span><span class="dl">'</span> <span class="p">)</span> <span class="p">)</span> <span class="p">?</span> <span class="dl">'</span><span class="s1">win</span><span class="dl">'</span> <span class="p">:</span> <span class="dl">'</span><span class="s1">fail</span><span class="dl">'</span><span class="p">;</span></code></pre></figure>

<p>This would become:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">isArrayShort</span> <span class="o">=</span> <span class="nx">myArray</span><span class="p">.</span><span class="nx">length</span> <span class="o">&lt;</span> <span class="mi">4</span><span class="p">,</span>
    <span class="nx">isStringCorrectLength</span> <span class="o">=</span> <span class="nx">myString</span><span class="p">.</span><span class="nx">length</span> <span class="o">&gt;</span> <span class="mi">2</span><span class="p">,</span>
    <span class="nx">isStringMatched</span> <span class="o">=</span> <span class="nx">myString</span> <span class="o">!==</span> <span class="dl">'</span><span class="s1">foobar</span><span class="dl">'</span><span class="p">,</span>
    <span class="nx">hasCorrectString</span> <span class="o">=</span> <span class="nx">isStringCorrectLength</span>
                       <span class="o">&amp;&amp;</span><span class="p">;</span> <span class="nx">isStringMatched</span><span class="p">,</span>
    <span class="nx">isPassed</span> <span class="o">=</span> <span class="nx">isArrayShort</span>
               <span class="o">||</span> <span class="nx">hasCorrectString</span><span class="p">,</span>
    <span class="nx">output</span> <span class="o">=</span> <span class="nx">isPassed</span> <span class="p">?</span> <span class="dl">'</span><span class="s1">win</span><span class="dl">'</span> <span class="p">:</span> <span class="dl">'</span><span class="s1">fail</span><span class="dl">'</span><span class="p">;</span></code></pre></figure>

<p>Ternary becomes much easier to read by a second party when used in this way; particularly when dealing with nested ternary statements. Of course, a good rule of thumb is to just avoid nesting ternary statements altogether.</p>

<h2 id="concerns_over_file_size">Concerns over file size</h2>

<p>In some languages, the size of the source code files you are creating can be pertinent to the performance of the final software. The obvious example of this is JavaScript files being served to a client.</p>

<p>In this instance, it is important not to sacrifice maintainability for optimisation. Should your files need optimising for final consumption, factor that optimisation away into your build or delivery mechanism. With JavaScript, this means minifying your code using an algorithm that can understand how to refactor it. Google’s Closure Compiler is a good example of one such tool; however, it still has limitations, and you may find it beneficial to write your own based around your coding standards.</p>

<h2 id="enforcing">Enforcing</h2>

<p>There is really only one way to enforce a coding standard, and that is exactly the same way you should be <em>developing</em> your coding standard; through code reviews.</p>

<h2 id="summary">Summary</h2>

<p>As my final word, I’d just like to point out that your mileage with this may vary wildly. This article is really only based on my own experience. However, whether you agree with everything here or not, I would hope you agree that easily maintainable code is the most important outcome of any good coding standard.</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Object-oriented JavaScript follow up part 2: Technical]]></title>
        <link href="https://nefariousdesigns.co.uk/object-oriented-javascript-follow-up-part-2-technical.html"/>
        <updated>2010-10-28T22:12:52+08:00</updated>
        <id>https://nefariousdesigns.co.uk/object-oriented-javascript-follow-up-part-2-technical</id>
        <content type="html"><![CDATA[<p>Following on from <a href="http://nefariousdesigns.co.uk/archive/2010/10/object-oriented-javascript-follow-up-part-1-method/">part 1 of my follow-up to “Object-oriented JavaScript”</a>, part 2 provides a technical update to some of the theories and examples.</p>

<p>Without further a-do, let’s jump in with the technical stuff:</p>

<!--more-->

<h2 id="a_quick_note_on_variable_declaration">A quick note on variable declaration</h2>

<p>The <code>var</code> declaration allows you to chain definitions in a comma separated list; what’s more that list can reference variables declared earlier in <em>the same list</em>.</p>

<p>Take this code as an example:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">el</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="err">“</span><span class="nx">my</span><span class="o">-</span><span class="nx">element</span><span class="err">”</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">elWidth</span> <span class="o">=</span> <span class="nx">el</span><span class="p">.</span><span class="nx">offsetWidth</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">elHeight</span> <span class="o">=</span> <span class="nx">el</span><span class="p">.</span><span class="nx">offsetHeight</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">elArea</span> <span class="o">=</span> <span class="nx">elWidth</span> <span class="o">*</span> <span class="nx">elHeight</span><span class="p">;</span></code></pre></figure>

<p>This could alternatively be written like so:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">el</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="err">“</span><span class="nx">my</span><span class="o">-</span><span class="nx">element</span><span class="err">”</span><span class="p">),</span>
    <span class="nx">elWidth</span> <span class="o">=</span> <span class="nx">el</span><span class="p">.</span><span class="nx">offsetWidth</span><span class="p">,</span>
    <span class="nx">elHeight</span> <span class="o">=</span> <span class="nx">el</span><span class="p">.</span><span class="nx">offsetHeight</span><span class="p">,</span>
    <span class="nx">elArea</span> <span class="o">=</span> <span class="nx">elWidth</span> <span class="o">*</span> <span class="nx">elHeight</span><span class="p">;</span></code></pre></figure>

<p>Personally, I prefer the latter method simply because it keeps my <code>var</code> declarations in one place (where possible) without endless repetition of the <code>var</code> keyword. However, this is simply a minor note on coding style, rather than something that can improve the operation of your code.</p>

<h2 id="understanding_object_oriented_scope">Understanding object-oriented scope</h2>

<p>As any experienced JavaScript coder knows, JavaScript is functionally scoped; this means any variables created within an object or function are only available within that object or function.</p>

<p>Simple, right?</p>

<p>Well no, there are actually a couple of complications to this behaviour that you should really understand:</p>

<h3 id="passing_by_reference">Passing by reference</h3>

<p>When passing arguments in JavaScript, it’s not immediately clear how those arguments are being handled internally. In fact, it is entirely dependant on the data-type of those arguments.</p>

<p>When passing arguments of type Number, String, or Boolean, JavaScript will pass them in <em>by value</em>. This means that the value stored in the argument will actually be a copy of the original value:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">accidentalFall</span><span class="p">(</span><span class="nx">count</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">count</span> <span class="o">=</span> <span class="nx">count</span> <span class="o">-</span> <span class="mi">1</span><span class="p">;</span> <span class="c1">// Remove one</span>
<span class="p">}</span>

<span class="kd">var</span> <span class="nx">greenBottles</span> <span class="o">=</span> <span class="mi">10</span><span class="p">;</span>

<span class="nx">alert</span><span class="p">(</span><span class="nx">greenBottles</span><span class="p">);</span> <span class="c1">// greenBottles is 10</span>

<span class="nx">accidentalFall</span><span class="p">(</span><span class="nx">greenBottles</span><span class="p">);</span> <span class="c1">// Pass by value</span>

<span class="nx">alert</span><span class="p">(</span><span class="nx">greenBottles</span><span class="p">);</span> <span class="c1">// greenBottles still 10</span></code></pre></figure>

<p>Passing in an object, however, passes the argument <em>by reference</em>. This means that, within the function, the argument is not a copy, but a reference—or link, if you like—to the original object. This means any members of that object are available within our function, and any changes to the object passed as an argument will be reflected <em>outside of the scope</em> of the function.</p>

<p>Actually, the way JavaScript handles references is another blog article in itself. Watch this space.</p>

<p>Here’s our example again:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">accidentalFall</span><span class="p">(</span><span class="nx">obj</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">obj</span><span class="p">.</span><span class="nx">count</span> <span class="o">=</span> <span class="nx">obj</span><span class="p">.</span><span class="nx">count</span> <span class="o">-</span> <span class="mi">1</span><span class="p">;</span> <span class="c1">// Remove one</span>
<span class="p">}</span>

<span class="kd">var</span> <span class="nx">greenBottles</span> <span class="o">=</span> <span class="p">{</span>
    <span class="na">count</span><span class="p">:</span> <span class="mi">10</span>
<span class="p">};</span>

<span class="nx">alert</span><span class="p">(</span><span class="nx">greenBottles</span><span class="p">.</span><span class="nx">count</span><span class="p">);</span> <span class="c1">// 10</span>

<span class="nx">accidentalFall</span><span class="p">(</span><span class="nx">greenBottles</span><span class="p">);</span> <span class="c1">// Pass by reference</span>

<span class="nx">alert</span><span class="p">(</span><span class="nx">greenBottles</span><span class="p">.</span><span class="nx">count</span><span class="p">);</span> <span class="c1">// 9</span></code></pre></figure>

<p>This is a subtle difference, but one, I think you’ll agree, that is important to understand.</p>

<h3 id="the_this_special_operator">The <code>this</code> special operator</h3>

<p>The <code>this</code> operator can be used to obtain a reference to the current context object and allows properties and methods within that execution context to be referenced. The context object can be considered a “hidden” parameter that is passed to any function.</p>

<p>There are four ways the context is made available to a function:</p>

<h4 id="implicitly_with_a_method">Implicitly with a method</h4>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">myObject</span><span class="p">.</span><span class="nx">method</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">arg1</span><span class="p">,</span> <span class="nx">arg2</span><span class="err">…</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Context here is myObject, and has been passed</span>
    <span class="c1">// implicitly.</span>
<span class="p">}</span></code></pre></figure>

<h4 id="implicitly_with_new">Implicitly with <code>new</code></h4>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">myConstructor</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">arg1</span><span class="p">,</span> <span class="nx">arg2</span><span class="err">…</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Here we have a new anonymous context</span>
    <span class="c1">// understandable as the instance…</span>
<span class="p">}</span>
<span class="c1">// …so the context here will be myObj</span>
<span class="kd">var</span> <span class="nx">myObj</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">myConstructor</span><span class="p">(</span><span class="nx">arg1</span><span class="p">,</span> <span class="nx">arg2</span><span class="err">…</span><span class="p">);</span></code></pre></figure>

<h4 id="explicitly_with_functioncall">Explicitly with <code>Function.call</code></h4>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">myObject</span><span class="p">.</span><span class="nx">method</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">arg1</span><span class="p">,</span> <span class="nx">arg2</span><span class="err">…</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Implicit context is myObject</span>
<span class="p">}</span>
<span class="c1">// Explicitly force context to anotherObject</span>
<span class="nx">myObject</span><span class="p">.</span><span class="nx">method</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="nx">anotherObject</span><span class="p">,</span> <span class="nx">arg1</span><span class="p">,</span> <span class="nx">arg2</span><span class="err">…</span><span class="p">);</span></code></pre></figure>

<h4 id="explicitly_with_functionapply">Explicitly with <code>Function.apply</code></h4>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">myObject</span><span class="p">.</span><span class="nx">method</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">arg1</span><span class="p">,</span> <span class="nx">arg2</span><span class="err">…</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Implicit context is myObject</span>
<span class="p">}</span>
<span class="c1">// Explicitly force context to anotherObject</span>
<span class="nx">myObject</span><span class="p">.</span><span class="nx">method</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">anotherObject</span><span class="p">,</span> <span class="p">[</span><span class="nx">arg1</span><span class="p">,</span> <span class="nx">arg2</span><span class="err">…</span><span class="p">]);</span></code></pre></figure>

<p>In general, JavaScript developers tend to rely on <em>implicit</em> context passing rather than <em>explicit</em>. However, there is one situation where this reliance falls down…</p>

<h3 id="a_common_problem">A common problem</h3>

<p>When registering event handlers against DOM nodes in JavaScript, the <code>this</code> context no longer references the method’s parent object, but rather the DOM node to which the event handler is registered.</p>

<p>The easiest way around this is to make sure the reference to the context object originally stored in <code>this</code> is maintained before defining the event handler:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">widget</span><span class="p">.</span><span class="nx">init</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">myButton</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="err">“</span><span class="nx">my</span><span class="o">-</span><span class="nx">button</span><span class="err">”</span><span class="p">),</span>
        <span class="nx">counter</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
        <span class="nx">that</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>

    <span class="nx">myButton</span><span class="p">.</span><span class="nx">onClick</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">that</span><span class="p">.</span><span class="nx">counter</span><span class="o">++</span><span class="p">;</span>
        <span class="k">this</span><span class="p">.</span><span class="nx">innerHTML</span> <span class="o">=</span> <span class="err">“</span><span class="nx">Clicked</span><span class="o">!</span><span class="err">”</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span></code></pre></figure>

<p>Further to this, according to Douglas Crockford, there is an error in the ECMAScript spec. that causes <code>this</code> to be set incorrectly for inner functions; something that he discusses in his article <a href="http://www.crockford.com/javascript/private.html">Private Members in JavaScript</a>:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">Container</span><span class="p">(</span><span class="nx">param</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">function</span> <span class="nx">dec</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">secret</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">secret</span> <span class="o">-=</span> <span class="mi">1</span><span class="p">;</span>
            <span class="k">return</span> <span class="kc">true</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="k">return</span> <span class="kc">false</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">this</span><span class="p">.</span><span class="nx">member</span> <span class="o">=</span> <span class="nx">param</span><span class="p">;</span>
    <span class="kd">var</span> <span class="nx">secret</span> <span class="o">=</span> <span class="mi">3</span><span class="p">;</span>
    <span class="kd">var</span> <span class="nx">that</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>

    <span class="k">this</span><span class="p">.</span><span class="nx">service</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">dec</span><span class="p">())</span> <span class="p">{</span>
            <span class="k">return</span> <span class="nx">that</span><span class="p">.</span><span class="nx">member</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">};</span>
<span class="p">}</span></code></pre></figure>

<p>Now, the "<code>var that = this</code>" technique is certainly a bone of contention amongst members of the JavaScript community, but I’m firmly on the fence in the whole discussion. Certainly my second example could be solved with a complex network of <code>Function.call</code> and <code>Function.apply</code> instead of <code>that.member</code>, but my first example would be somewhat more difficult.</p>

<p>Personally, I feel if Doug Crockford—a developer with many years more experience and infinitely more JS knowledge than myself—says it’s ok, then I’m fine with it.</p>

<h2 id="garbage_collection">Garbage collection</h2>

<p>As JavaScript is a scripting language, it implicitly allocates memory for objects, strings, variables, and so on as it runs. <em>Garbage collection</em> is the process by which the JavaScript engine detects when those pieces of memory are no longer reachable—that is, they could not possibly ever be used again—and reclaims the memory.</p>

<p>The ECMAScript specification (of which JavaScript is an implementation) doesn’t include a definition on how a JS engine should handle garbage collection, so although each JavaScript engine includes garbage collection—memory usage would quickly snowball if they didn’t—they all handle it somewhat differently.</p>

<p>Some engines are better than others; Google’s V8 is exceptionally good, where as the IE JScript engine is notoriously bad (often resulting in memory leaks).</p>

<h2 id="closures">Nested functions and closures</h2>

<p>JavaScript allows the nesting of functions, creating nested scope blocks that inherit scope from their parents all the way up to the global scope.</p>

<p>Take this code for example (there are much better ways of doing this; this method is only in the interests of illustration):</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">appendList</span><span class="p">(</span><span class="nx">list</span><span class="p">,</span> <span class="nx">itemPrefix</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">getListItem</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">return</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="nx">itemPrefix</span> <span class="o">+</span> <span class="nx">x</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="nx">j</span> <span class="o">=</span> <span class="nx">list</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">j</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">getListItem</span><span class="p">(</span><span class="nx">i</span><span class="p">).</span><span class="nx">innerHtml</span> <span class="o">+=</span> <span class="err">‘</span> <span class="p">[</span><span class="nx">done</span><span class="p">]</span><span class="err">’</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span></code></pre></figure>

<p>In the above example <code>getListItem</code> is a nested function within <code>appendList</code>. This means it inherits everything within the scope of <code>appendList</code>. As a result of this, the inner function is able to make use of the <code>itemPrefix</code> parameter that is passed to its parent without it needing to be passed in as another parameter on <code>getListItem</code>.</p>

<p>When JS automatically garbage collects the <code>appendList</code> function, it will find no <em>external</em> references to the <code>getListItem</code> function and will garbage collect that as well.</p>

<p>This is a useful feature of JavaScript, and allows for fairly advanced l<a href="http://stackoverflow.com/questions/16501/what-is-a-lambda-function">ambda functions</a> (anonymous functions), as well as providing a useful tool for namespacing library functions.</p>

<p>However, if, upon garbage collection, JavaScript finds an external reference to a nested function, it creates a closure of scope; thus maintaining access to all the variables required within the scope of that function.</p>

<p>This is known as <strong>a closure</strong>.</p>

<h3 id="common_usage">Common usage of closures</h3>

<p>The most common occurrence of a closure in JavaScript is when declaring event callbacks. This is simply due to the fact that the callback function is referenced within the event listener once registered.</p>

<p>However, it’s important to understand that many modern libraries, plugin architectures, and plugins themselves also make use of closures, and understanding <em>how</em> they use them can mean the difference between controlled and uncontrolled memory usage.</p>

<h3 id="invisible_pitfalls_are_invisible">Invisible pitfalls are invisible</h3>

<p>It’s obvious when you think about it, but all closures have a potentially high memory imprint as they are maintaining much more than just their constituent parts. What’s more, because of their inherent avoidance of garbage collection, they are maintained until they are manually destroyed either by the code, or by a page refresh.</p>

<h2 id="prototypal_inheritance">Prototypal inheritance</h2>

<p>I did discuss prototypal inheritance in <a href="http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-javascript/">my original Object-Oriented Javascript article</a>, however I just want to go into a little more detail here.</p>

<p>In a prototypal system, objects are supposed to inherit from objects; unlike in a <em>classical inheritance</em> system where classes inherit from classes and <em>instantiate</em> objects. JavaScript has no class (pun intended).</p>

<p>Prototypal inheritance is actually simpler than classical inheritance once you get your head around it. You don’t need to define classification, so your code is smaller and less redundant since objects inherit from other more general objects. It is a model of <a href="http://en.wikipedia.org/wiki/Differential_inheritance"><em>differential inheritance</em></a>; i.e. each level of inheritance only adds the differences with its parent.</p>

<p>Unfortunately, JavaScript is a bit confused about its prototypal nature, and wants to fit in with the other scripting languages by pretending to like The Beatles and by making itself more attractive to classically trained programmers by introducing the <code>new</code> operator.</p>

<p>This means that:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="k">new</span> <span class="nx">myConstructor</span><span class="p">();</span></code></pre></figure>

<p>produces an object that inherits from <code>myConstructor.prototype</code>.</p>

<p>This indirection means that JavaScript actually has a pretty ugly constructor pattern and most new JavaScript developers never really get to grips with the inheritance model at all.</p>

<p>However, all that has changed with the all singing, all dancing advent of JavaScript 1.8.5 (The New Shit™), which introduces the <code>Object.create</code> method:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">human</span> <span class="o">=</span> <span class="p">{</span>
    <span class="na">legs</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span>
    <span class="na">arms</span><span class="p">:</span> <span class="mi">2</span>
<span class="p">};</span>

<span class="kd">var</span> <span class="nx">tim</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">human</span><span class="p">,</span> <span class="p">{</span>
    <span class="na">tall</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
    <span class="na">fat</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
    <span class="na">overInflatedSenseOfSelfImportance</span><span class="p">:</span> <span class="kc">true</span>
<span class="p">});</span></code></pre></figure>

<p>Mmm tasty, but since JS 1.8.5 only seems to be implemented in Firefox 4 (still in beta), don’t get all excited just yet.</p>

<p>If you want something similar in your own code, you can implement the following for a similar approach (and still kiss goodbye to ever having to use the <code>new</code> operator again):</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">inherits</span> <span class="o">!==</span> <span class="dl">'</span><span class="s1">function</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
    <span class="nb">Object</span><span class="p">.</span><span class="nx">inherits</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">parent</span><span class="p">,</span> <span class="nx">child</span><span class="p">)</span> <span class="p">{</span>
        <span class="kd">function</span> <span class="nx">temp</span><span class="p">()</span> <span class="p">{};</span>
        <span class="nx">temp</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="nx">parent</span><span class="p">.</span><span class="nx">prototype</span><span class="p">;</span>
        <span class="nx">child</span><span class="p">.</span><span class="nx">super_</span> <span class="o">=</span> <span class="nx">parent</span><span class="p">.</span><span class="nx">prototype</span><span class="p">;</span>
        <span class="nx">child</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">temp</span><span class="p">();</span>
        <span class="nx">child</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="kd">constructor</span> <span class="o">=</span> <span class="nx">child</span><span class="p">;</span>
    <span class="p">};</span>
<span class="p">}</span>

<span class="nb">Object</span><span class="p">.</span><span class="nx">inherits</span><span class="p">(</span><span class="nx">parentConstructor</span><span class="p">,</span> <span class="nx">childConstructor</span><span class="p">);</span></code></pre></figure>

<p>What’s more, this DIY version will allow you access to any superclass’ implementations of a particular method like so:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">childConstructor</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">foo</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">a</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Here’s some of that scope correction we discussed</span>
    <span class="c1">// earlier…</span>
    <span class="nx">childConstructor</span><span class="p">.</span><span class="nx">super_</span><span class="p">.</span><span class="nx">foo</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">a</span><span class="p">);</span>

    <span class="c1">// Other code</span>
<span class="p">};</span></code></pre></figure>

<p>This code is a mix of the <code>goog.inherits</code> function—included in the Closure library—and the <code>Object.create</code> outline by Crockford in his <a href="http://javascript.crockford.com/prototypal.html">article on prototypal inheritance</a>.</p>

<h2 id="javascript_design_patterns">JavaScript design patterns</h2>

<p>Taking all this into account, we can start developing some incredibly useful design patterns that make use of prototypal inheritance, closures, and JavaScripts nuances of scope.</p>

<p>In fact, several have already been developed within the JavaScript community:</p>

<h3 id="javascript_namespacing">JavaScript namespacing</h3>

<p>To avoid the perils of globally scoped variables and functions, it is advisable to create a single global object for the purposes of namespacing the rest of your code. This is relatively simple to achieve:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">NEF</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nx">NEF</span> <span class="o">||</span> <span class="p">{};</span></code></pre></figure>

<p>This command tests for the existence of a <code>NEF</code> object at the global scope, and if evaluated to true, returns that object. Otherwise, it creates a new object using the object literal syntax.</p>

<p>You may now assign any further variables or modules to your namespace:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">NEF</span><span class="p">.</span><span class="nx">myAttribute</span> <span class="o">=</span> <span class="err">‘</span><span class="nx">foo</span><span class="err">’</span><span class="p">;</span>
<span class="nx">NEF</span><span class="p">.</span><span class="nx">myFunction</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="err">…</span>
<span class="p">};</span></code></pre></figure>

<h3 id="module_pattern">Module pattern</h3>

<p>The JavaScript module pattern was first proposed by Doug Crockford as a means of enforcing public and private object members through the use of closures.</p>

<p>My preferred variation on the pattern is such:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">NEF</span><span class="p">.</span><span class="nx">Module</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="c1">// Private members</span>
    <span class="kd">var</span> <span class="nx">privateAttribute</span><span class="p">;</span>

    <span class="kd">function</span> <span class="nx">privateMethod</span><span class="p">()</span> <span class="p">{</span>
        <span class="nx">alert</span><span class="p">(</span><span class="dl">'</span><span class="s1">Private method called.</span><span class="dl">'</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="kd">var</span> <span class="nx">pub</span> <span class="o">=</span> <span class="p">{</span>
        <span class="c1">// Public members</span>
        <span class="na">publicAttribute</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>

        <span class="na">publicMethod</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
            <span class="c1">// Private members are in scope here</span>

            <span class="nx">privateMethod</span><span class="p">();</span>

            <span class="c1">// Public members are addressable through the 'pub' object.</span>

            <span class="nx">pub</span><span class="p">.</span><span class="nx">publicAttribute</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="nx">pub</span><span class="p">;</span>
<span class="p">}();</span></code></pre></figure>

<p>This method simple uses a closure to maintain private variables in the scope of the returned <code>pub</code> object. The trick of this technique is the use of the <code>()</code>, right at the end of the code, after the parent function definition, which causes the function to run immediately and return the <code>pub</code> object.</p>

<h3 id="jquery_plugins">jQuery plugins</h3>

<p>The jQuery plugin architecture also makes use of closures to do something quite similar to the Module Pattern above. However, jQuery plugins are specifically namespaced to the jQuery object itself:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">$</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Private members</span>
    <span class="kd">var</span> <span class="nx">debugMode</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>

    <span class="kd">function</span> <span class="nx">debug</span><span class="p">(</span><span class="nx">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">debugMode</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span><span class="p">;</span> <span class="p">}</span>
        <span class="k">if</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">console</span> <span class="o">&amp;&amp;</span> <span class="nb">window</span><span class="p">.</span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">){</span>
            <span class="nb">window</span><span class="p">.</span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">msg</span><span class="p">);</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="nx">alert</span><span class="p">(</span><span class="nx">msg</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="nx">$</span><span class="p">.</span><span class="nx">fn</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span>
        <span class="na">myPlugIn</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">config</span><span class="p">)</span> <span class="p">{</span>
            <span class="kd">var</span> <span class="nx">defaults</span> <span class="o">=</span> <span class="p">{</span>
                <span class="err">…</span>
            <span class="p">};</span>

            <span class="k">if</span> <span class="p">(</span><span class="nx">config</span><span class="p">)</span> <span class="p">{</span>
                <span class="nx">$</span><span class="p">.</span><span class="nx">extend</span><span class="p">(</span><span class="nx">defaults</span><span class="p">,</span> <span class="nx">config</span><span class="p">);</span>
            <span class="p">}</span>

            <span class="k">this</span><span class="p">.</span><span class="nx">each</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>

            <span class="p">});</span>

            <span class="k">return</span> <span class="k">this</span><span class="p">;</span>
        <span class="p">},</span>

        <span class="na">publicMethod</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
            <span class="err">…</span>
        <span class="p">}</span>
    <span class="p">});</span>
<span class="p">})(</span><span class="nx">jQuery</span><span class="p">);</span></code></pre></figure>

<p>Alternatively, should you wish to only include a single public method, you can avoid <code>jQuery.fn.extend</code> by instead making use of <code>jQuery.fn</code> for definition:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">$</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Private members</span>
    <span class="kd">var</span> <span class="nx">debugMode</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>

    <span class="kd">function</span> <span class="nx">debug</span><span class="p">(</span><span class="nx">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">if</span><span class="p">(</span><span class="nx">debugMode</span> <span class="o">&amp;&amp;</span> <span class="nb">window</span><span class="p">.</span><span class="nx">console</span> <span class="o">&amp;&amp;</span> <span class="nb">window</span><span class="p">.</span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">){</span>
            <span class="nb">window</span><span class="p">.</span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">msg</span><span class="p">);</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="nx">alert</span><span class="p">(</span><span class="nx">msg</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="nx">$</span><span class="p">.</span><span class="nx">fn</span><span class="p">.</span><span class="nx">myPlugIn</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">config</span><span class="p">)</span> <span class="p">{</span>
        <span class="kd">var</span> <span class="nx">defaults</span> <span class="o">=</span> <span class="p">{</span>
            <span class="err">…</span>
        <span class="p">};</span>

        <span class="k">if</span> <span class="p">(</span><span class="nx">config</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">$</span><span class="p">.</span><span class="nx">extend</span><span class="p">(</span><span class="nx">defaults</span><span class="p">,</span> <span class="nx">config</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="k">this</span><span class="p">.</span><span class="nx">each</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>

        <span class="p">});</span>

        <span class="k">return</span> <span class="k">this</span><span class="p">;</span>
    <span class="p">};</span>
<span class="p">})(</span><span class="nx">jQuery</span><span class="p">);</span></code></pre></figure>

<p>In this code we can see that jQuery is passed to an anonymous function, that is run immediately, as the parameter <code>$</code>. The anonymous function provides a scope block for the plug-in code, thus preventing potential headaches from variable naming clashes across shared code. The plug-in functions themselves are then created as closures so that they have access to the private variables and functions within that outer anonymous function. These plug-in variables are then bound to the passed in jQuery instance <code>$</code> using jQuery’s own built in extension functions.</p>

<p>This is actually quite a clever use of closures, although it does have the potential for memory leaks and excessive memory usage if variables and references aren’t kept in check. With that in mind, it’s often a very good idea to profile your jQuery plugins to understand what might need tidying up.</p>

<h3 id="custom_events">Custom events</h3>

<p>Most modern JavaScript libraries include a mechanism for defining your own custom events. A custom event is merely a bespoke event, defined in your code, that other event-handler functions may be bound to. This custom event may then be triggered by you at any given point of execution in the code.</p>

<p>The custom event architecture is an implementation of the Observer Pattern, in which an object maintains a list of dependant “observers” which it notifies automatically of any state changes. In JavaScript, the object maintaining the list is our event, and the “observers” are the event handlers.</p>

<p>Using custom events in your own code provides a useful binding for other developers’ code. The event itself is loosely coupled to the event handlers, thus, <em>additional</em> event handlers can be added or removed by third-party code.</p>

<p>For more information on custom events, I’d recommend having a look at the documentation for the library of your choice. Here are few links:</p>

<ul>
<li><a href="http://api.jquery.com/bind/">jQuery custom events: .bind()</a></li>
<li><a href="http://developer.yahoo.com/yui/event/#customevent">YUI2 custom events: The CustomEvent object</a></li>
<li><a href="http://www.yahooapis.com/yui/3/event/#customevent">YUI3 custom events</a></li>
</ul>

<h2 id="summary">Summary</h2>

<p>So that’s the technical addendum to my 2006 post. Hopefully, that should serve to bring the article up to date, and correct a few of my previous errors. As always, comments and corrections are welcome via the comment form below.</p>

<p>Originally I had intended posting this article in two parts, however, it has continued to grow even as I write it. For this reason, the third and final part of this follow-up series will look at what’s on the horizon for JavaScript development, including how GoogleBot deals with JavaScript, the importance of supporting a core experience (where JavaScript is unavailable), server-side JavaScript, and architecting JavaScript applications.</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Object-Oriented JavaScript Follow-Up Part 1: Method]]></title>
        <link href="https://nefariousdesigns.co.uk/object-oriented-javascript-follow-up-part-1-method.html"/>
        <updated>2010-10-08T17:43:08+08:00</updated>
        <id>https://nefariousdesigns.co.uk/object-oriented-javascript-follow-up-part-1-method</id>
        <content type="html"><![CDATA[<p>Back in May, 2006, I wrote an article entitled <a href="http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-javascript/">Object Oriented JavaScript</a>. It was an exercise in both writing a useful tutorial, and a brain-dump of various things I had learned about writing object-oriented code on the client side. It quickly became apparent—as the article was linked to from a multitude of my favourite web standards development sources—that the tutorial itself was helpful; the comments burgeoned, and the traffic rocketed.</p>

<p>When I read that article now, however, it bothers me. The tutorial is still good although the information within is somewhat dated; and my personal experience, knowledge, and general approach to writing JavaScript has changed quite drastically. The fact that the article still receives a consistently high number of unique visitors on a daily basis, when I no longer agree with all the content within it, bothers me even more. With that in mind, I have decided to write an update that looks at OOJS as I would currently use it.</p>

<p>The resulting post has become quite extensive, so I’ve decided to split it into two separate articles. This first one will cover some development theory, whilst the second will dive into JavaScript coding specifics.</p>

<!--more-->

<h2 id="a_note_on_the_name">A note on the name</h2>

<p>A friend of mine recently quoted this little gem in his Twitter stream:</p>

<blockquote>
  <p>Java is to JavaScript as Ham is to Hamster.</p>
</blockquote>

<p>Enough said.</p>

<h2 id="is_it_object_oriented">Is it object-oriented?</h2>

<p>In my original article I stated that JavaScript was <em>not</em> an object-oriented language, but rather an object-<em>based</em> language. This was entirely unfair on JavaScript, and I’d like to fix that:</p>

<p>JavaScript <em>is</em> an object-oriented language. However, it breaks away from more conventional object-oriented languages by implementing prototypal inheritance, instead of classical inheritance. This is a Very Good Thing™ (although that seems to be a matter of opinion). More on that later.</p>

<h2 id="first_principles_for_javascript_programming">First principles for JavaScript programming</h2>

<p>Before I start, let me be clear that there are first principles of programming that are language agnostic. We’re going to look at a couple of those, but I’d also like to discuss a few of the more JavaScript specific principles first; those that relate to the cross-browser web standards environment. Finally, I’m aware that I’m really only scratching the surface of some of these topics. I don’t really want to muddy the water here by waxing lyrical on good development practices, so if you’re after more depth, I’d recommend researching them via the search engine of your choice:</p>

<h3 id="proper_separation_of_the_behavioural_layer">Proper separation of the behavioural layer</h3>

<p>Above everything else, it’s important to keep your content and markup (HTML), presentation (CSS), and behavioural (JavaScript) layers separate. Why is that important? Well if one or more of those layers are missing or broken (with the obvious exception of the core HTML), the others should still function as intended. Ultimately this makes presentation and behaviour optional, and a user might turn them off—via their browser settings—should they so desire. Alternatively, the user may include custom presentation or behaviour to aid a particular use-case.</p>

<p>In JavaScript, proper separation requires making use of the DOM to bind behaviour to HTML elements via element identifiers (i.e. the <code>id</code> or <code>class</code> attribute) in your source code. The alternative would be to write JS directly into the HTML, via event attributes such as <code>onClick=””</code> or via the <code>javascript:</code> pseudo-protocol in the <code>href</code> attribute. This is not a good practice and I heartily recommend against it.</p>

<h3 id="graceful_degradation">Graceful degradation</h3>

<p>Graceful degradation is a well known software engineering concept which involves writing your code to take advantage of awesome feature X, unless awesome feature X is unavailable, in which case degrade to use slightly-less-awesome feature Y (assuming that too is available).</p>

<p>In web development terms this might mean making use of an amazing JavaScript date picker widget on a text-based input box, and just degrading to server-side date validation if JS is not turned on in the browser. It could also mean making use of the latest CSS3 styling techniques but degrading to use CSS2 techniques in less capable browsers.</p>

<p>In short; build everything in the most up to date browser, making use of all it’s wonderful modern features, and then go back and make sure the site is still usable when any of those features are not.</p>

<p>The problem with approaching the issue from this direction, however, is that you are saying to your users: “You (or your browser) are incapable of handling the full experience we want to present, so here’s a cut-down version.” This pretty much flies in the face of user-centric design, and good user experience. With that in mind, we’d be better using…</p>

<h3 id="progressive_enhancement">Progressive enhancement</h3>

<p>Progressive enhancement involves approaching the problem from the other direction. You should design for the user-agent with the least capabilities and add functionality for more capable browsers afterwards.</p>

<p>In web terms this means developing and designing with nothing but the base features of HTML in mind, and then enhancing those features (or the features of the browser interpreting that HTML) by attaching CSS and JS to the HTML via element identifiers like IDs and classes.</p>

<p>The final outcome of these two approaches might be very similar, but the subtle difference is that you are giving more attention to the less capable user-agent when you progressively enhance.</p>

<p>The most common use-case for progressive enhancement is the support of a non-JS experience.</p>

<h3 id="dry_dont_repeat_yourself">DRY (Don’t Repeat Yourself)</h3>

<p>Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. This means abstracting code into shared functions and objects whenever you find you are repeating yourself, and attempting to maintain a single source of truth in every aspect of your system.</p>

<p>DRY is a well known paradigm in software engineering, and as such, should be applied in every detail of your JavaScript code.</p>

<h3 id="refactor_early_refactor_often">Refactor early, refactor often</h3>

<p>Further to the principle of DRY, it is important that if you spot a potential issue in your JavaScript code you fix it. The more small refactors you do, the less time-consuming big refactors you are likely to need to do later on.</p>

<p>Once you’re refactoring often, you’ll be able to…</p>

<h3 id="make_it_work_make_it_right_make_it_fast">Make it work, make it right, make it fast</h3>

<p>The first iteration of your code should only look to reach the level of functionality defined in the functional specification. Once this has been achieved, refactor to improve the <em>way</em> it works—so the code is “right” in your opinion. This may very well mean a complete overhaul of architecture, but you will be able to concentrate much more specifically on that since you already have it working. The final stage in this development cycle is to optimise your code for performance and efficiency; premature optimisation is a fundamental mistake in development.</p>

<h3 id="useful_resources">Useful resources</h3>

<p>When it comes to general development, there are a veritable plethora of resources out there, but my recommended starting point is the book <a href="http://www.amazon.co.uk/gp/product/020161622X?ie=UTF8&amp;tag=gamersite-21&amp;linkCode=as2&amp;camp=1634&amp;creative=19450&amp;creativeASIN=020161622X"><strong>The Pragmatic Programmer</strong>, by Andrew Hunt and David Thomas</a>. This book outlines quite a few paradigms that should get you thinking about the way you develop.</p>

<h2 id="important_things_to_understand">Important things to understand</h2>

<h3 id="pure_javascript">Pure JavaScript</h3>

<p>In this age of JavaScript libraries and frameworks, it’s important to make sure you understand core JavaScript functions, objects, and methods. Although your library of choice may clean up any cross-browser issues you may encounter, it is always important to understand exactly how you are interacting with JavaScript as a language.</p>

<h4 id="useful_resources2">Useful resources:</h4>

<p>The <a href="http://developer.mozilla.org/en/JavaScript">Mozilla Developer Centre section on JavaScript</a> is an invaluable reference resource when writing pure JavaScript. Also, make sure you own a copy of <a href="http://www.amazon.co.uk/gp/product/0596101996?ie=UTF8&amp;tag=gamersite-21&amp;linkCode=as2&amp;camp=1634&amp;creative=19450&amp;creativeASIN=0596101996"><strong>JavaScript: The Definitive Guide</strong> by David Flanagan</a>.</p>

<h3 id="the_dom">The DOM</h3>

<p>The Document Object Model is an entirely separate beast to JavaScript, but is implemented natively within it. There are also DOM libraries for other languages that implement the W3 DOM specification when dealing with XML and SGML files.</p>

<p>Understanding the DOM in JavaScript is essential when designing and developing interactions with your HTML and CSS. Thankfully all JavaScript libraries abstract out the pitfalls of DOM scripting so that you don’t have to, but as before, it’s still important for you to understand <em>how</em> so that you can maximise your efficiency in using said library.</p>

<h4 id="useful_resources3">Useful resources:</h4>

<p>Once again the Mozilla Developer Centre provides an excellent <a href="https://developer.mozilla.org/en/DOM">DOM reference section</a>, although it is slightly skewed in favour of the Gecko browser engine. You can also find plenty of <a href="http://www.w3.org/DOM/">information on the DOM at the W3C site</a>.</p>

<h3 id="interaction_with_the_browser">Interaction with the browser</h3>

<p>When writing client-side JavaScript, it is important to take into account how HTML, CSS, and JavaScript interact with the browser directly. At every available opportunity, you should attempt to make sure you are not contradicting the browser, and that you are not rewriting interactions that are already well handled by the browser and operating system.</p>

<p>A good example of this is to make sure you do not break the “back” button. Often this can be achieved by simply using the <code>window.location.replace()</code> method to control which pages appear in the browser history.</p>

<h2 id="libraries">Libraries</h2>

<p>Using libraries in JavaScript has become standard practice. A JavaScript library exists to save time and effort, and to provide a single source of truth (as discussed earlier) for many common tasks within that language.</p>

<p>A JavaScript library provides you a toolbox full of handy devices to make your life easier. It needs to be treated as such, and not as a language in its own right. It is very important to understand the core structures of JavaScript, and how the library of your choice interacts within those structures and your own code.</p>

<p>Every library is different and has its own pros and cons. I’m not going to go into my opinion of those here; perhaps that’s something for another post. They do, however, all interact somewhat differently with JavaScript, and it’s important to understand how the library you choose does that specifically.</p>

<h2 id="summary">Summary</h2>

<p>Hopefully that should get you in the right frame of mind to develop high quality JavaScript code. In the second half of this article I will be looking at specific use of JavaScript in regard to object-orientation.</p>

<p><a href="http://nefariousdesigns.co.uk/archive/2010/10/object-oriented-javascript-follow-up-part-2-technical/">Continue reading part 2 of my object-oriented JavaScript follow-up&hellip;</a></p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[jQuery Accordion]]></title>
        <link href="https://nefariousdesigns.co.uk/jquery-accordion.html"/>
        <updated>2010-08-22T18:06:57+08:00</updated>
        <id>https://nefariousdesigns.co.uk/jquery-accordion</id>
        <content type="html"><![CDATA[<div style="background: #fcc; padding: 10px 10px 0; border: 1px solid #c33; margin: 1.2em 0;"><strong style="color: #c33;">Update November 2010:</strong> Documentation for this jQuery Accordion can now be found here:

<a href="http://projects.timhuegdon.com/jquery-accordion/">jQuery Accordion - Tim Huegdon's Projects</a>
</div>

<p>Following on from my post about my <a href="http://nefariousdesigns.co.uk/archive/2010/08/jquery-carousel/">jQuery Carousel</a>, here’s another widget: an accordion.</p>

<p>Until recently, I’ve usually used my friend and ex-colleague <a href="http://www.i-marco.nl/weblog/jquery-accordion-menu-redux2/">Marco’s jQuery accordion plug-in</a>. However, whilst prototyping some stuff for work, I noticed a rather uncomfortable animation jump which, after some investigation, seems to be <a href="http://jqueryfordesigners.com/slidedown-animation-jump-revisited/">a well documented issue with jQuery’s <code>slideDown()</code> method</a>. Since I was prototyping at the time, I quickly knocked up my own very basic accordion and, over time, it grew into something more.</p>

<p>The current version of my accordion follows a recent refactor–there are still several features I’d like to add–but for now I’m happy to let it out into the wild.</p>

<!--more-->

<h2>Demo</h2>

<p>As was the case with my carousel, I’d definitely recommend taking a look at my <a href="http://nefariousdesigns.co.uk/projects/widgets/accordion/">page of example accordion implementations</a>. This should give you a reasonable idea of the capabilities of the script; and as I update the widget, I’ll update this page.</p>

<h2>Source Code</h2>

<p>All the source code for the accordion–and the example page above–is available in the following GitHub repository:</p>

<p><a href="http://github.com/nefarioustim/jquery-accordion">jQuery Accordion – GitHub repository</a></p>

<h2>Implementation</h2>

<h3>HTML</h3>

<p>Basic HTML for the accordion is as follows:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"accordion"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li&gt;</span>
        <span class="nt">&lt;h3&gt;</span>Handle 1<span class="nt">&lt;/h3&gt;</span>
        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"panel"</span><span class="nt">&gt;</span>
            <span class="ni">&amp;hellip;</span>
        <span class="nt">&lt;/div&gt;</span>
    <span class="nt">&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;</span>
        <span class="nt">&lt;h3&gt;</span>Handle 2<span class="nt">&lt;/h3&gt;</span>
        <span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"panel"</span><span class="nt">&gt;</span>
            <span class="ni">&amp;hellip;</span>
        <span class="nt">&lt;/ul&gt;</span>
    <span class="nt">&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;</span>
        <span class="nt">&lt;h3&gt;</span>Handle 3<span class="nt">&lt;/h3&gt;</span>
        <span class="nt">&lt;p</span> <span class="na">class=</span><span class="s">"panel"</span><span class="nt">&gt;</span>
            <span class="ni">&amp;hellip;</span>
        <span class="nt">&lt;/p&gt;</span>
    <span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span></code></pre></figure>

<p>For each panel in the accordion, you will require both a panel (the content of our accordion pane) AND a handle (an item that is clicked to open a panel). These can be anything you want as you can specify the jQuery selector used for each as part of your configuration. By default, the selector for handles is “h3”, and the selector for panels is “.panel”. Obviously that was fairly specific to my original implementation, so I’ll look to fix that in the near future.</p>

<p>Notice that, because we’re specifying our own selectors, we’re able to use flexible HTML for either the panel or the handle. However, it’s also worth remembering that the accordion script injects a link around the contents of whatever you specify as the handle, so that the handle becomes focusable and keyboard navigable. If you are likely to end up with invalid markup (i.e. the inline link wrapped around a block level element), you may get unpredictable behaviour cross-browser.</p>

<h3>CSS</h3>

<p>The included CSS is really only a reset style-sheet for the list elements within the accordion. You will probably already be achieving this with your own reset stylesheet, but you can add the following link to the head of your document:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">"stylesheet"</span> <span class="na">href=</span><span class="s">"css/accordion.core.css"</span> <span class="na">type=</span><span class="s">"text/css"</span> <span class="na">charset=</span><span class="s">"utf-8"</span><span class="nt">&gt;</span></code></pre></figure>

<h3>JavaScript</h3>

<p>To activate the accordion in your pages, you will require both jQuery and the accordion script itself to be included at the bottom of your page, just before the closing <code></code> tag, but before any script that applies the accordion to a jQuery object.</p>

<p>A default implementation would look like this:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html">    <span class="ni">&amp;hellip;</span>
    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">"text/javascript"</span> <span class="na">src=</span><span class="s">"js/jquery-1.4.2.min.js"</span> <span class="na">charset=</span><span class="s">"utf-8"</span><span class="nt">&gt;&lt;/script&gt;</span>
    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">"text/javascript"</span> <span class="na">src=</span><span class="s">"js/jquery.accordion.2.0.js"</span> <span class="na">charset=</span><span class="s">"utf-8"</span><span class="nt">&gt;&lt;/script&gt;</span>
    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">"text/javascript"</span><span class="nt">&gt;</span>
        <span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">.accordion</span><span class="dl">"</span><span class="p">).</span><span class="nx">accordion</span><span class="p">();</span>
    <span class="nt">&lt;/script&gt;</span>
<span class="nt">&lt;/body&gt;</span></code></pre></figure>

<p>As with my carousel, you can configure the accordion more specifically by passing a configuration object to the <code>.accordion()</code> method:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">"text/javascript"</span><span class="nt">&gt;</span>
    <span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">.accordion</span><span class="dl">"</span><span class="p">).</span><span class="nx">accordion</span><span class="p">({</span>
        <span class="dl">"</span><span class="s2">handle</span><span class="dl">"</span><span class="p">:</span>           <span class="dl">"</span><span class="s2">h3</span><span class="dl">"</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">panel</span><span class="dl">"</span><span class="p">:</span>            <span class="dl">"</span><span class="s2">.panel</span><span class="dl">"</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">speed</span><span class="dl">"</span><span class="p">:</span>            <span class="mi">200</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">easing</span><span class="dl">"</span><span class="p">:</span>           <span class="dl">"</span><span class="s2">swing</span><span class="dl">"</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">accordion</span><span class="dl">"</span><span class="p">:</span>        <span class="kc">true</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">toggle</span><span class="dl">"</span><span class="p">:</span>           <span class="kc">false</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">activeClassPanel</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">open</span><span class="dl">"</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">activeClassLi</span><span class="dl">"</span><span class="p">:</span>    <span class="dl">"</span><span class="s2">active</span><span class="dl">"</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">lockedClass</span><span class="dl">"</span><span class="p">:</span>      <span class="dl">"</span><span class="s2">locked</span><span class="dl">"</span>
    <span class="p">});</span>
<span class="nt">&lt;/script&gt;</span></code></pre></figure>

<p>Note: The above options are all the defaults.</p>

<p>Parameters for the configuration object are as follows:</p>

<table style="border-collapse: collapse; font-size: 100%;">
    <thead>
        <tr>
            <th>Option</th>
            <th>Value</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>handle</td>
            <td>A selector that specifies the element that will contain the injected link to trigger the opening of each panel.</td>
        </tr>
        <tr>
            <td>panel</td>
            <td>A selector that specifies the panel element to open and close.</td>
        </tr>
        <tr>
            <td>speed</td>
            <td>The animation speed for opening and closing. Defaults to 200.</td>
        </tr>
        <tr>
            <td>easing</td>
            <td>The animation easing for opening and closing. Defaults to "swing".</td>
        </tr>
        <tr>
            <td>accordion</td>
            <td>A boolean to specify whether other items should close when one is opened. If this is false, all items work independently.</td>
        </tr>
        <tr>
            <td>toggle</td>
            <td>A boolean to specify whether a handle can toggle opening and closing of an element.</td>
        </tr>
        <tr>
            <td>activeClassPanel</td>
            <td>HTML class for the active panel.</td>
        </tr>
        <tr>
            <td>activeClassLi</td>
            <td>HTML class for the active parent <code><li>&lt;/code&gt;&lt;/td&gt;
        &lt;/tr&gt;
        <tr>
            <td>lockedClass</td>
            <td>HTML class used to lock any panels open.</td>
        </tr>
    &lt;/tbody&gt;
&lt;/table&gt;

I've tried to cover all the above concepts in the examples page. However, feel free to comment requests for more information, or bug reports. Alternatively, you can fork and append the GitHub repo, or register bugs there.
</li></code></td></tr></tbody></table>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[jQuery Carousel]]></title>
        <link href="https://nefariousdesigns.co.uk/jquery-carousel.html"/>
        <updated>2010-08-19T06:16:40+08:00</updated>
        <id>https://nefariousdesigns.co.uk/jquery-carousel</id>
        <content type="html"><![CDATA[<div style="background: #fcc; padding: 10px 10px 0; border: 1px solid #c33; margin: 1.2em 0;"><strong style="color: #c33;">Update November 2010:</strong> Documentation for this jQuery Carousel can now be found here:

<a href="http://projects.timhuegdon.com/modern-carousel/">Modern Carousel - Tim Huegdon's Projects</a>
</div>

<p>Recently I’ve had the need to build several jQuery widgets, because, no matter how many already exist in the wild, they never seem to have all the features I require. Reinventing the wheel? Well yes, but there’s no harm if the current wheel doesn’t fit the vehicle.</p>

<p>Further to that, building widgets with various JavaScript libraries is actually pretty good fun, and is definitely a good way of familiarising yourself with that particular library. Having recently moved from using YUI to the more widely used jQuery, these widgets have aided my education.</p>

<p>So without further ado, here’s the first: the carousel.</p>

<!--more-->

<h2>Demo</h2>

<p>Take a look at the <a href="http://nefariousdesigns.co.uk/projects/widgets/carousel/">page of example carousels</a> first, to see the various implementation options.</p>

<h2>Source Code</h2>

<p>You can find all the source code hosted on GitHub here, with tarballs and zips:</p>

<p><a href="http://github.com/nefarioustim/modern-carousel">Modern Carousel — GitHub repository</a></p>

<h2>Implementation</h2>

<h3>HTML</h3>

<p>The core HTML of the carousel should look something like this:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"carousel"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"clip"</span><span class="nt">&gt;</span>
        <span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"horizontal"</span><span class="nt">&gt;</span>
            <span class="nt">&lt;li&gt;</span>…<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>…<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>…<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>…<span class="nt">&lt;/li&gt;</span>
        <span class="nt">&lt;/ul&gt;</span>
    <span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;/div&gt;</span></code></pre></figure>

<p>The <code>carousel</code>, <code>clip</code>, and <code>horizontal</code> classes are all used by both the core CSS and the JavaScript to build the carousel. As a result, they are required features.</p>

<p>The carousel <code>div</code> must be the direct parent of the clip <code>div</code>, which in turn must be the direct parent of the <code>ul</code> element. The current version of the carousel script does not support the use of an ol, but it’s one of the features on my todo list.</p>

<p>For a vertical carousel, you should substitute the <code>horizontal</code> class with <code>vertical</code>.</p>

<h3>CSS</h3>

<p>The only required CSS for the carousel, is the <samp>carousel.core.css</samp> file:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">"stylesheet"</span> <span class="na">href=</span><span class="s">"css/carousel.core.css"</span> <span class="na">type=</span><span class="s">"text/css"</span> <span class="na">charset=</span><span class="s">"utf-8"</span><span class="nt">&gt;</span></code></pre></figure>

<p>My examples also include a CSS skin file that applies some styling to the carousel controls. Feel free to reuse this, or poke at it to come up with your own styles:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">"stylesheet"</span> <span class="na">href=</span><span class="s">"css/carousel.skin.css"</span> <span class="na">type=</span><span class="s">"text/css"</span> <span class="na">charset=</span><span class="s">"utf-8"</span><span class="nt">&gt;</span></code></pre></figure>

<h3>JavaScript</h3>

<p>To add the JavaScript, you simply need to include the script—along with jQuery—somewhere on your page. It’s best to include scripts at the bottom of your pages, before the closing body tag, as some browsers can delay loading of the rest of the page whilst the script loads.</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">"text/javascript"</span> <span class="na">src=</span><span class="s">"js/jquery-1.4.2.min.js"</span> <span class="na">charset=</span><span class="s">"utf-8"</span><span class="nt">&gt;&lt;/script&gt;</span>
<span class="nt">&lt;script </span><span class="na">type=</span><span class="s">"text/javascript"</span> <span class="na">src=</span><span class="s">"js/jquery.carousel.2.0.js"</span> <span class="na">charset=</span><span class="s">"utf-8"</span><span class="nt">&gt;&lt;/script&gt;</span></code></pre></figure>

<p>Once you’ve done that, you can simply apply the <code>carousel()</code> method to any jQuery object, like so, to get the default options:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">"text/javascript"</span><span class="nt">&gt;</span>
            <span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">.carousel</span><span class="dl">"</span><span class="p">).</span><span class="nx">carousel</span><span class="p">();</span>
<span class="nt">&lt;/script&gt;</span></code></pre></figure>

<p>Alternatively, you can configure the carousel by passing it a configuration object like so:</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">"text/javascript"</span><span class="nt">&gt;</span>
    <span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">.carousel</span><span class="dl">"</span><span class="p">).</span><span class="nx">carousel</span><span class="p">({</span>
        <span class="dl">"</span><span class="s2">loop</span><span class="dl">"</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">autoplay</span><span class="dl">"</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">hovercontrols</span><span class="dl">"</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
        <span class="dl">"</span><span class="s2">hoverpause</span><span class="dl">"</span><span class="p">:</span> <span class="kc">true</span>
    <span class="p">});</span>
<span class="nt">&lt;/script&gt;</span></code></pre></figure>

<p>Parameters for the configuration object are as follows:</p>

<table style="border-collapse: collapse; font-size: 100%;">
<thead>
<tr>
<th scope="col">Option</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>visiblePanes</td>
<td>The number of panes that are visible in the clipping area.</td>
</tr>
<tr>
<td>panesToMove</td>
<td>The number of panes to move the carousel when next/previous are clicked.</td>
</tr>
<tr>
<td>pagination</td>
<td>Boolean value to turn on or off pagination.</td>
</tr>
<tr>
<td>speed</td>
<td>Speed of the transition between panes.</td>
</tr>
<tr>
<td>loop</td>
<td>Boolean value to specify if the carousel loops after the final pane has been reached.</td>
</tr>
<tr>
<td>autoplay</td>
<td>Boolean value to specify whether the carousel autoplays.</td>
</tr>
<tr>
<td>hovercontrols</td>
<td>Boolean value to specify if the controls only display when hovering over the carousel.</td>
</tr>
<tr>
<td>hoverpause</td>
<td>Boolean value that activates pause when hovering the mouse over the carousel.</td>
</tr>
<tr>
<td>delay</td>
<td>The delay, in milliseconds, between transitions when the carousel is playing.</td>
</tr>
<tr>
<td>transition</td>
<td>A reference to a transition function defined at $.fn.carousel. E.g. "yourTransitionHere" would reference a function defined at $.fn.carousel.yourTransitionHere.</td>
</tr>
</tbody>
</table>

<p>For more on the transition hooks, it’s probably best to take a look at the code. When I have more time, I’ll look at updating the GitHub wiki with details myself.</p>
]]></content>
    </entry>
    
    <entry>
        <title type="html"><![CDATA[Controlling DHCP for VMWare Fusion VMs]]></title>
        <link href="https://nefariousdesigns.co.uk/controlling-dhcp-for-vmware-fusion-vms.html"/>
        <updated>2010-03-09T06:42:45+08:00</updated>
        <id>https://nefariousdesigns.co.uk/controlling-dhcp-for-vmware-fusion-vms</id>
        <content type="html"><![CDATA[<p>This week I built a brand new Mac for work. This meant I also needed to install VMWare Fusion and knock up a couple of virtual machines for development. Everything was working as expected until I tried using the same VMs at home, and discovered a complete lack of connectivity to—and within—the VMs, despite having active network and internet access on the host OS. After a little investigation, I discovered the issue:</p>

<p>When I’ve used VMWare Fusion in the past, my VMs have all been assigned IPv4 addresses in the range 172.16.0.0 through 172.31.255.255, via DHCP (the 20-bit block of RFC1918). This has always suited me fine, and has meant I’ve been able to assign host file mapping entries for those IP addresses with relative confidence since the addresses have never changed, even after reboots.</p>

<p>However, on the new Mac, I was surprised to find my VMWare VMs being assigned IPv4 addresses in the range 192.168.0.0 through 192.168.255.255 (the 16-bit block of RFC1918). As you can imagine, this could cause a certain degree of havoc if you’re LAN is <em>also</em> assigning DHCP IP addresses in that range. This is exactly what was happening in my case—and on both my work LAN and my home LAN—so VMWare was having to change the IPs each time I changed network.</p>

<p>To fix this issue, all I needed to do was tell VMWare to use a specific range of IP addresses when assigning DHCP. Unfortunately, VMWare doesn’t make this particularly easy (despite including a handy network configuration script). So here’s what you have to do…</p>

<!--more-->

<h2>A quick word on VMWare Fusion networking</h2>

<p>Before I jump in with the “how to”, let me just take a moment to explain how networking works in VMWare Fusion:</p>

<p>VMWare sets up two network interfaces during installation, plus a bridge from Fusion to your host’s active network interface. The two network interfaces that are configured are “vmnet1”–the host-only network–and “vmnet8”–the NAT network interface. It is the latter of the two that we need to configure for control over VM DHCP.</p>

<h2>Resetting the network configuration</h2>

<p>Firstly, make sure you have shut down all your VMs (even the headless ones), and that the VMWare GUI isn’t running. We’ll also need to make sure, before we start our configuration, that we’re in a predictable state for all the configuration files used by VMWare. Handily, VMWare Fusion supplies a network interface configuration script that will allow us to do exactly that.</p>

<p>VMWare records a bunch of information–in regard to DHCP and the vmnets–in a file called “locations”. To begin with, we’ll need to delete that file so that it is regenerated later:</p>

<pre><samp>$ <kbd>cd /Library/Application\ Support/VMWare\ Fusion/</kbd>
$ <kbd>rm -f locations</kbd></samp></pre>

<p>Following that, we run the handy configuration Perl script, which will automatically answer it’s own questions with the default answers:</p>

<pre><samp>$ <kbd>sudo ./vmware-config-net.pl</kbd>

Configuring a NAT network for vmnet8.

'ping' -q -t 10 192.168.119.1 &gt; /dev/null status = 2
The subnet 192.168.119.0/255.255.255.0 appears to be unused.

The file /Library/Application Support/VMware Fusion/vmnet8/dhcpd.conf that this program was about to install already exists. Overwrite? [yes]

The file /var/db/vmware/vmnet-dhcpd-vmnet8.leases that this program was about to install already exists. Overwrite? [yes]

The file /var/db/vmware/vmnet-dhcpd-vmnet8.leases~ that this program was about to install already exists. Overwrite? [yes]

…</samp></pre>

<p>I haven’t included all the output here, but it continues on for a while.</p>

<p>Once you have a prompt again, it’s time to restart the network services with these update values (even though they’re not going to be final):</p>

<pre><samp>$ <kbd>sudo ./boot.sh --restart</kbd></samp></pre>

<p>This will give you a “Shutting down VMware Fusion:” message, followed by a “Starting VMware Fusion:” message.</p>

<p>Once you get your prompt back, make sure the network interfaces have been set up correctly by running the interface configurator:</p>

<pre><samp>$ <kbd>ifconfig</kbd>

…

vmnet8:	flags=8863 mtu 1500
		inet 192.168.119.1 netmask 0xffffff00 broadcast 192.168.119.255
		ether 00:50:56:c0:00:08
vmnet1: flags=8863 mtu 1500
		inet 172.16.225.1 netmask 0xffffff00 broadcast 172.16.225.255
		ether 00:50:56:c0:00:01

…</samp></pre>

<p>You should see something like the above, even if the addresses are slightly different. As long as the vmnet8 and vmnet1 interfaces are showing, we’re up and running again.</p>

<h2>Defining your IP range</h2>

<p>Remember that “locations” file we junked earlier? That’s where we need to define our IP ranges so that the network configuration script can work its magic. Following our little clean-up, that file should now be nice and simple, and ready for our changes. To do that, you’ll need to edit with root permissions:</p>

<pre><samp>$ <kbd>mate locations</kbd></samp></pre>

<p>I’m using TextMate, which will prompt me for my admin password when I save the file. If you’re using an editor like vi or vim, you’ll need to sudo:</p>

<pre>$ <kbd>sudo vim locations</kbd></pre>

<p>The settings you need to define in the locations file are as follows:</p>

<pre><samp>VNET_8_HOSTONLY_HOSTADDR
VNET_8_HOSTONLY_NETMASK
VNET_1_HOSTONLY_HOSTADDR
VNET_1_HOSTONLY_NETMASK
VNET_1_HOSTONLY_SUBNET</samp></pre>

<p>I defined mine like so, with the third digit matching the vmnet to which it is assigned, just so I have a point of reference if I need it:</p>

<pre><samp>…
answer VNET_8_HOSTONLY_HOSTADDR <kbd>172.16.8.1</kbd>
answer VNET_8_HOSTONLY_NETMASK 255.255.255.0
…
answer VNET_1_HOSTONLY_HOSTADDR <kbd>172.16.1.1</kbd>
answer VNET_1_HOSTONLY_NETMASK 255.255.255.0
answer VNET_1_HOSTONLY_SUBNET <kbd>172.16.1.0</kbd>
…</samp></pre>

<p>Once we’ve saved our changes, we simply need to reset the network configuration using the same Perl script as earlier:</p>

<pre><samp>$ <kbd>sudo ./vmware-config-net.pl</kbd>

Configuring a NAT network for vmnet8.

Configuring a host-only network for vmnet1.

The host-only network is currently configured to use the private subnet 172.16.1.0/255.255.255.0. Do you want to keep these settings? [yes]</samp></pre>

<p>Finally, restart VMWare Fusion daemons and reconfigure the network interfaces:</p>

<pre><samp>$ <kbd>sudo ./boot.sh --restart</kbd></samp></pre>

<p>Once that is complete, VMWare is configured to use your defined range of IP addresses for both its vmnets. You can check this by running the interface configurator again:</p>

<pre><samp>$ <kbd>ifconfig</kbd>
…
vmnet8: flags=8863 mtu 1500
        inet 172.16.8.1 netmask 0xffffff00 broadcast 172.16.8.255
        ether 00:50:56:c0:00:08 
vmnet1: flags=8863 mtu 1500
        inet 172.16.1.1 netmask 0xffffff00 broadcast 172.16.1.255
        ether 00:50:56:c0:00:01</samp></pre>

<h2>Summary</h2>

<p>So now you can configure your vmnets in VMWare Fusion to use a predictable range of IP addresses. That, as they say, is that.</p>
]]></content>
    </entry>
    
</feed>