Altogether, CSS attribute selectors provide more fine-grained control to style markup. For example, you can choose to style anchor tags that link to external pages differently - no need to needlessly suffer classitis.
This post carries on from yesterday’s so if you haven’t read, get to it! As you may have guessed from the name, the revealing module pattern is a variant of the module pattern already covered. However, it has proven so popular as to warrant specific mention in most to every discussion of design patterns.
The two takeaways from the module pattern were,
We can choose the visibility of our variables and methods, either public or private,
We use object literal notation to set out public variables and methods.
This is reasonably effective though a bit crude: We have the rather unfortunate practice of writing private entities differently to public ones, the latter use object literal notation. Furthermore it can lead to needless repetition in our code if we wish to reference public entities from another. The revealing module pattern leads to much cleaner code as all our methods and variables, regardless of visibility, are written together. We then return - reveal - the entities we wish to make public. For instance,
Altogether, a bit nicer to look at. There may be some concerns, as with the vanilla module pattern, regarding the difficulty of testing or patching methods which refer to private entities.
Similar to my previous posts inthis series, the module pattern is perhaps better described as a general best-practice than as by a distinct structure. Unsurprisingly then, there are a number of common variations in the wild such as using import mixins and exports. At its core it rests on a very simple principle we will see a lot more of in the future: Using object literal notation to assign property values and method to our class-like objects. This can be particularly useful as a (rather crude) way of setting properties as either public or private. An example using the IIFE pattern,
This allows us to namespace private variables to the closure. However, this particular pattern can lead to some challenges if we wish to change the visibility or a particular variable at a later date: We will have to make a change at each place the variable was used. This frustration inspired the more sophisticated revealing module pattern, which I’ll cover tomorrow.
Unlike the other patterns we will come across, the singleton pattern is not defined so much by a specific written structure, we could just as well talk about either object literals and function closures. All we want is something that provides a globally available object instance. Carrying on from my previous post on the constructor pattern, we can create a singleton example, shamelessly hoisted from Rob Dobson’s post on the subject,
This is admittedly quite crude, and highlights the key issue with globally available variables: we have no particular control where and how a given House instance is set. Although not specific to the singleton pattern, we can make it far more sophisticated by making use the IIFE pattern to make the contents private.
We can append key to objects using the “dot” syntax,
We create a new object instance using the new keyword.
Append variable values to an object instance using the this keyword,
Append shared object methods to the Prototype object.
Altogether we would get something,
Though simple in its execution, depending on the nature of the problem at hand the constructor pattern could lead to a lot of unnecessary bloat. In the coming weeks, we will see constructors again and again in some form or another, as they often form a smaller part of more elaborate patterns.
In this post I want to cover the general what and why of design patterns. Design patterns are popular, well-supported recipes for writing code. Sticking to a design pattern, as opposed to going completely freestyle can have a number of benefits. Arguably the most important advantage to using a design pattern is the larger community support that they engender: These patterns stick to a known structure, which is more readily communicated, and tend to follow best-practices. Furthermore, the structure they provide often helps prevent making costly mistakes with consequences further down the line. This can be contrasted with so-called “anti-patterns”, which true to their name go against the main advantages of following a design pattern. This includes such sins as namespace pollution, using less efficient non-native methods, and inline script.
Although there is always a kind of specificity in any code, after all we want solutions not just good practices, there are a few commonalities when it comes to writing a true design pattern. These include:
The practicality of the solution,
How well it follows best practices,
How easily a newcomer can come to grips with the pattern.
The latter point naturally leads to a strong emphasis on good documentation and community support, which is something of a virtuous circle. In other words, a design pattern is only a pattern in so far as it follows a solid set of principles.
I hope to work my way through a high-level overview of some of the more popular design patterns in the coming months.
Created by Jonathan Snook, SMACSS, or Scalable and Modular Architecture for CSS, is one of a handful of working practices to promote the writing of consistent, maintainable, and understandable CSS. There might be further considerations to push towards more efficient code, however as the savings in processor time are minimal it is probably best to neglect this metric in favour of saving programmer time. SMACSS is distinguished from its competitors such as OOCSS and BEM, by its emphasis on using selector names which fall into categories determined by their type and function. Sticking to vanilla CSS, SMACSS starts from the principle of sticking to class selectors as much as possible to prescribing rules relating to, naming conventions, state changes, selector depth, and modularity.
Sticking to Classes
We want to stick to using classes, and classes only. Classes are reusable, which is good for modularity and future-proofing, and as for styling purposes ids give us no added benefits in terms selector performance. Although this practice places an absolute premium on our naming convention, provided we are consistent and plan ahead, using classes alone should not put us at any disadvantage.
SMACSS splits CSS selectors into five different categories: base, layout, module, state, and theme. This is our first line of defence in maintaining a DRY stylesheet, the categories relate as follows,
Base rules are defaults, usually provided by something like normalize.css. These are an exception to the rule above, as they usually apply to element tag selectors.
Layout rules are the containers for our module rules, these relate to the spatial divisions within our page. The class selectors for these rules follow the pattern l-<name> e.g. l-fixed.
Module rules are the mainstay of our stylesheet. These are highly reusable parts of stylesheet, we put anything we want shared across multiple distinct elements here. There isn’t such a straightforward naming convention to follow due to the frequency of use, however we do want to stick to semantically meaningful, generic, and reusable class names.
State rules determine styling for state changes such as user interactions, selector names follow the pattern is-<state-name> e.g. is-active.
Theme rules can add an additional layer of styling for customisation or typography.
To elaborate a bit on terming selectors “semantically meaningful”, class names should indicate how selectors relate to content on the page, and how they relate to one another. For instance indicating parent-child nesting by a shared prefix, we will cover this in more detail below. This practice both rules out using element selectors in general - although HTML5 gives us some help here - and more broadly, ensures that our class names clues us onto the function of a given selector.
Naming state style rules is one thing, but applying them usefully is quite another. SMACSS doesn’t so much prescribe a particular way of rendering state changes so much as putting an emphasise on using the most appropriate way of handling the state change in question in keeping with our considerations for modularity etc. For instance, if we were to represent a state change using class names we would want to ensure the code is not heavily dependent on the DOM structure: rather than target a parent container with our CSS selectors stick with a sibling selector instead.
The aim of the game is to go for as shallow a depth with as few selectors as possible. Taken together, this looks to make the styling as modular as possible: it will ultimately be very generic and be less dependent on the DOM structure.
A good practice is to avoid duplication, for instance the following,
should be a cue to introduce a joint class name to target both elements.
The added benefit of using few selectors is that we needn’t make use of ids or !important overrides unless absolutely necessary. We would simply add in another class name to get the desired styling to render, this is important when considering sub-modules below.
We’ve pretty much touched on modularity throughout, which is not particularly surprising considering its importance in SMACSS (it’s in the name!). However, we have not discussed sub-modules: when needs be, we might want to distinguish a particular module based on its location or use within the page e.g. a sidebar as opposed to a pop-up, with a common parent class selector. As before we want to keep our code as generic as possible. To do so we would use an additional class selector with a name that reflects its parent container, perhaps by using a shared prefix.
Admittedly there is very much more to cover, such as how to make the most of preprocessors using SMACSS and some other formatting considerations. Thankfully there is very much more information on the topic, not least the official website and book. I myself am very new to the practice, and am sure to return to the topic in the future.
Recently I had to deal with a situation that I’ve some how managed to avoid for a surprisingly long time: merge conflicts due to mismatched binary files, in this case image files. Now Git being Git, there are a number of equally viable ways of resolving any given problem - and thinking back, I do slightly regret not giving more time to investigating the arguably cool-sounding git mergetool. In general, binary files can be a bit of headache with Git due to the difficulty of dealing with their diffs. This can be a cause for concern due to the need to manually resolve some issues further down the line, although there is help out there.
That said, diffs aren’t so much a problem with image files. In my case, I made use of git checkout using the --ours and --theirs options, for instance git checkout --ours -- myfile.png. Appending one or the other option to git checkout allows you to checkout your or their committed file respectively. This saves you the effort of resolving the merge conflict manually.
If my twitter feed is anything to go by, lately I’ve been spending some time looking at CSS regression testing using BackstopJS - more on that to come. Invariably though it led to some minor hiccups that really messed up my git-chi. For those who haven’t used BackstopJS in it’s current, rather nascent state, it can be a bit messy to get started for a relative noob like myself. Upon installation, its files sit in a bower_components/backstopjs directory, which is a-ok.
However, annoyances quickly followed as I tried to selectively ignore or track subdirectories and files of the new backstopjs directory. The project comes with it’s very own .gitignore file, which is all very well, unless of course you want to place everything into the one gitignore file at the root directory of your project. The solution I’ve come across is not particularly clean, but is well documented. For instance if you have a directory structure,
where we may very well want to track main.js, but ignore everything else. The documentation above makes it clear that we can’t just get away with adding an exception for main.js,
It is not possible to re-include a file if a parent directory of that file is excluded. Git doesn’t list excluded directories for performance reasons, so any patterns on contained files have no effect, no matter where they are defined.
In other words, we need to specify the parent directory of every file we wish to track. Following this logic our .gitignore should look something like this,
An unfortunate consequence of this is that we would have to specific every parent directory for a given file if we wanted particularly fine-grained control over tracked files.
In the process I also learnt a neat trick with the git status command. If I wish to see all my untracked files, not just directories as per default, I need to add -u option. This will print out all the individual untracked files, which is particularly useful when specifying specific files as above.
I’ve spent the past few days sorting out my configuration for a new macbook, one hurdle has been sorting out my Sublime development environment. Users of Sublime Text, myself included, do not typically use symlinked dotfiles to store their settings as is discussed here, but rather copy over settings files wholesale.
The simplest and safest way - it may not be wise to copy plugins - to do so,
From your old workstation, make a copy of your current Preferences.sublime-settings and Package Control.sublime-settings both of which should be found in Packages/User/, and send to your new workstation,
From your new workstation, install Package Control,
Place the two copied files in the User directory.
My particular story did not end there: On an initial startup of Sublime I was greeted with alert “The package specified, Jasmine, is not available” or in other words we have a reference to a defunct package. To fix this, I deleted the named package from Package Control.sublime-settings.
Of course this is perhaps the most labour intensive way about it. Having searched around after the fact there are many alternatives to automate the process including this shell script.