Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

July 03 2012


Design for Readability

Compared to their print counterparts, the web versions of many magazines give readers a decidedly poor reading experience. Most websites follow a lackluster design model. Will digital publications ever be able to compete with the reading experience that printed ones have bought readers to expect?

Web designers have it rough. Translating ideas from designs to fully-coded websites is a process fraught with challenge and, due to factors often outside of their control, most find themselves in a perpetual state of compromise. Fortunately – for writers, readers, and everyone in between – the gap between what we can imagine and what we can create is closing, pointing the way to a more beautiful, readable web.

The Standard Content Design Model

Everyone who has used the internet is familiar with what I call the Standard Content Design Model (or SCDM for short): the prototypical blog format, where “content” fills one, long, vertical column. It dominates nearly all digital publications (Hi, UX Booth readers). The SCDM is so versatile that it’s used to display search results, news feeds …anything you can imagine!

It’s the norm largely because, by default, that’s how browsers present text. It looks like this:

Three versions of the SCDM.

Cause, meet effect

A number of milestones in the history of the web have had the power to change browsers and, potentially, uproot the SCDM. With the release of CSS in December 1996, for example, designers gained the ability to quickly, easily and consistently define the layout of their designs. In theory, this was a death knell for the SCDM.

But not in practice.

Perhaps early web designers were so focused on making elements of their designs (headers, main navs, sub navs, footers, sidebars, links, ads, etc.) behave consistently that the content – the one, true variable – became an afterthought. Another (more likely) cause is due to the popularity content management systems (CMSs) gained as a consequence. Instead of having to worry about coding, CMS + CSS allowed publishers to swap out designs with the click of a button. This left them with more time to focus on content.

How would you like your content? Vertical? Vertical? or Vertical?

For those of you who’ve built a site or two before: there’s nothing new here. This is the current state of affairs with regards to publishing. And back when WordPress was only used for blogs, it was good enough.

Today, though, WordPress is used to maintain large websites with many different types of content. Applying a custom design to one post, or to a whole set of posts, is difficult and time consuming. As a result, ventures outside the SCDM are still rare – a full sixteen years after the release of CSS!

Why? It probably has to do with how we think about content in the first place.

Design before content

In the standard content model, the design (form) of a site precedes its content (function). Many people agree that this approach is off piste; function should come before form because, in many ways, it serves to define it. Jeffrey Zeldman writes:

Content precedes design. Design in the absence of content is not design, it’s decoration.

Jeffrey Zeldman

Instead of designing for content in a way that gives users the most enjoyable reading experience, web designers have been making designs (using the “standard” model), and plopping their content into it. As an afterthought.

This mindset seems to be the primary difference between designing for the web and designing for print. On the web, design often precedes content, yielding to the SCDM and the subpar reading experience that comes with it. In print design, content comes before layout and readability shines.

Head to head

Let’s investigate this discrepancy courtesy of Esquire magazine. Take this article about Bruce Jenner, father of the youngest two Kardashian’s and former decathlon Olympic gold medalist, in the June/July 2012 issue of Esquire.

On their website, the article is a perfect example of the SCDM in action. The page has 3 columns, with navigation on the left, links and ads on the right, and the article straight down the middle. The text of the article, the central content of that page, is crowded on all sides by links and ads that distract me when I’m reading. Nevermind that the article is paginated, which studies have shown decreases readability.

Now let’s take a look at the magazine version. First of all, I’ve got to include more images because the intriguing title page is a two-page spread with a photo. (Side note: was that Wheaties box designed before I was born?)

The style of this spread makes me want to read more. Varsity-style lettering is a fitting choice when your subject is a former Olympic athlete and the color scheme of the typography and section dividers match well with the photo, giving everything a sense of balance.

Turning the page, we come to the article itself. Again, custom typography plays a major role in the design. It serves to separate sections of the story as well as for decoration and contrast.

The photo here you may recognize from the screenshot of the web version, but it’s much bigger and clearer in the print version (you can’t even enlarge it on the site). The text of the story has more room to breathe, here, because it takes up all of the real-estate, instead of being confined to a fixed width down the middle of the page and crowded further in by ads, links and nav items the way the website is. Finally, the text in the magazine layout is broken up into columns so that the reader’s eyes can travel naturally from top to bottom, and from left to right.

Overall, the magazine makes for a much more pleasant reading experience. The website serves its purpose – the same content in print is available online – but if you were given both options, which would you read? I have to wonder if the poor design of their web content has a secret agenda. Maybe they designed it poorly to drive readers to buy the magazine, instead.

Designing for readability

All is not lost, though. We’ve recently seen the addition of media queries, responsive typography and web fonts to our toolbox.

Thanks in part to these milestones, the web continues to be a playground of innovation. Some designers are pushing the boundaries of what it means to properly Design around their content.

I Love Typography

I Love Typography makes custom designs for each new article they post. This one is called The Design of a Signage Typeface.

The font is big enough to embrace, the different background colors make it easy for the reader to keep their place, and the two column format allows our eyes to travel in both directions, a familiar experience because that is how we read print.

I Love Typography doesn’t always go with a two column format in a custom design, but I wish they would because it reduces the amount of scrolling. It seems such a waste of perfectly good real estate when there is only one column on the left (as they use here).

I Love Typography’s custom-designed blog posts are also designed responsively. See for yourself. (Note that on a mobile device the design reverts to one column for obvious reasons.)

Jason Santa Maria

Jason Santa Maria is famous for redesigning his website with each new piece of content he publishes. His candy series is no exception, and this one in particular, formatted in two, wonderfully even columns, is a sweet treat. Again, emulating multi-column magazine formats improves the reading experience, and requires less scrolling, which is nice.

Similarly, Santa Maria’s archive uses three columns, allowing readers to scan quickly across months and years to find what they’re looking for. As an added bonus, articles with custom layouts are accompanied by screenshots, to help the visually inclined find them more quickly.

Craig Mod

Craig Mod’s journal has an interesting design. I usually dislike type set this small, but because the columns are well spaced and each section is appropriately titled it’s enjoyable. The titles serve to break up the sections, so user can quickly scan the content. Users often scan – as opposed to read – web content, so it’s important to include subtitles.

The Great Discontent

The Great Discontent publishes artist interviews. Each interview starts with a huge header image that takes up the entire browser, much like the Esquire article we examined above (the magazine version, not the web version). No confusion who this interview is going to be about.

The interview itself occupies the middle column of the design. The top of the left column is used for the “About” section, where you can learn more about the artist being interviewed. The right column and the left column below the “About” section reprint memorable quotes from the interview, or relevant quotes from related sources. The reprinting of quotes and inclusion of relevant outside material are an old magazine technique that allows readers to scan to find the good stuff and important takeaways. It also helps hook the reader. Maybe you weren’t interested until you read that quote halfway down. You might go back and read the whole thing after that.

Usually about halfway through the interview, a second image or video is included. Notice how these images, accompanied by quotes and links, take up the whole three columns, effectively interrupting the interview itself. This is a nice break for readers. It allows them to rest their eyes, but if they want to keep reading, there’s no one stopping them from scrolling.

Finally, the previous and next arrows are displayed on the right and left at all times. These arrows subtly inform the user that there are more interviews to be read without distracting from the reading experience the way a sticky top or side nav would. It also avoids burying the prev/next links at the bottom of the article, in the usual way, so that even the reader who didn’t read all the way to the bottom knows that there is more good content to be found.

A more readable future

Fortunately, web technology develops rapidly. Over the next few years it will become easier and easier for designers to give content the attention it deserves. In the meantime, designers can do their part by putting in the extra time to design more readable content. Yes, there are hurdles to jump, but the tools are available now and some industry pioneers are already leading the way.

Developers can speed the process by focusing their energies on creating more flexible methods to format readable content (flexible templates, more custom content types, on-the-fly paragraph division to form even columns out of long content, etc) that don’t break designs and layouts.

And if designers and developers learn to work closely together, anything is possible.

The post Design for Readability appeared first on UX Booth.

November 19 2011


A Guide To Improve Your Website’s Readability Through Colors

Colors exist not only to make your site look pretty. Colors have a more important function – to make your site usable. A pretty site is not something to object against but when pretty colors make the text on site unreadable, this isn’t something to be proud of. This is why a designer must always think of readability first and beauty second when choosing the colors for a site.

When you think about the number of available colors, it looks easy to pick a bunch of them that go well together and are readable. If you stick with classic background colors, such as white (FFFFFF), or very light gray (F5F5F5, FAFAFA, FCFCFC, etc.) and foreground colors such as black (000000), or very dark gray (080808, 050505, 030303, etc.), or the lightest/darkest pair of the main color (i.e. red, green, blue or whatever color you are using) on your site you might wonder why readability is an issue at all. However, sooner or later you will get fed up with these classic combinations everybody is using and you will want something fancier.

This is where your problems start. These fancier combinations might be pleasing esthetically but in terms of readability they are not necessarily winners. Of course, nobody says it is impossible to find good combinations outside the group of frequently used ones. With the right tools I will mention in this article finding colors with good readability becomes much easier. However, before we go to the tools, let’s review some of the basics of colors and readability.

Color Brightness and Color Difference Determine Readability

Web design always boils down to numbers and the way you crunch them. Readability isn’t an exception. The guidelines for readability are set by the W3C and even though they (as almost any other W3C specification currently in use) are work in progress, there is a lot of criticism of the methodology, and researchers prove it wrong, it is the best we have and we stick with them. Here is the basic formula, as defined by W3C:

“Two colors provide good color visibility if the brightness difference and the color difference between the two colors are greater than a set range.

Color brightness is determined by the following formula:

((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000
Note: This algorithm is taken from a formula for converting RGB values to YIQ values. This brightness value gives a perceived brightness for a color.

Color difference is determined by the following formula:

(maximum (Red value 1, Red value 2) – minimum (Red value 1, Red value 2)) + (maximum (Green value 1, Green value 2) – minimum (Green value 1, Green value 2)) + (maximum (Blue value 1, Blue value 2) – minimum (Blue value 1, Blue value 2))

The rage for color brightness difference is 125. The range for color difference is 500.”

These formulas might look pretty cryptic and hard to understand but when you use a tool that calculates the values for you, for instance the Colour Text Legibility tool, or the Colour Contrast tool, you easily get an answer if the colors you have chosen pass the test or not.

However, unless you feel like reinventing the wheel and hunting for color combinations with good brightness and difference, you can stick to the safe choices that have already been developed for you, such as dark text on a light background.

The Golden Classics: Dark Text on a Light Background

All equal, dark text on a light background provides the best readability. Of course, it depends on which colors you choose but the highest readability ratio is achieved when you use black on white:

Black on White

As you see from the screenshot above, readability varies depending on the font size (and obviously the font itself) and a good tool will tell you if the combination you have chosen is good for titles only or for both titles and body text. Generally, the larger the font size, the more readable it is. Don’t count on this too much because as you know, for body text 10-14 is the most used size (i.e. is relatively small), which means that for body texts you won’t be able to use a color that is readable for titles.

Black on white isn’t the only great combination. If you want to see more examples of excellent to good contrast when you use white as a background color, check the first table in this article.

White backgrounds are pretty common but sometimes you will want more color. For instance, some very pale shades of red, green, yellow, blue, etc. make great backgrounds when used with black or another very dark foreground color. These combinations are not as readable as when you use black but still the ratio is good. Here are some examples of combinations where the background color is different from white and the foreground color is different from black:

For Differing Background and Foreground

Ivoryblack (#292421) on lavenderblush1 (#FFF0F5)

Midnight blue (#191970) on ghostwhite (#F8F8FF)

Sgi gray 12 (#1E1E1E) on mintcream (#F5FFFA)

One small trick many designers use to make a page more readable (and more pleasing to the eye, too) is to employ gradients for background. A gradient of white and a very pale shade of any other color works best. Well, you can’t measure its brightness and contrast using the readability formulas but if the two colors that constitute the gradient separately have good readability values, when combined, the result is even better.

The Intricacies of Dark Background

Dark backgrounds can be very depressing – not only because dark colors are traditionally related to bad things in life, at least in the Western cultures but also because they are a lot of pain to choose a readable foreground color to go with.
The problem comes from the fact that even if your contrast values are good, this doesn’t make it easier to read the text. White on black might have the best ratio but it causes eye fatigue pretty soon. As Pabini Gabriel-Petit writes, “On a black background, the high-chroma colors yellow (#FFFF00), green (#00FF00), cyan (#00FFFF), and magenta (#FF00FF) provide the best contrast.”

Dark Background Choices

If these color combinations, no matter how readable they are supposed to be, give you the feeling you are back in the 80s or early 90s when monitors were green and the text was orange, you are not alone. I have never used such an antique monitor, so I am not able to tell from experience but always when I land on a site with a dark background and light text I have to read, I get the feeling it is a time machine that takes me back two or three decades ago and my eyes are the first to object.

OK, dark backgrounds might be cute but when I have to read a 2,000+ word article (and the comments under it), this makes me cry – literally! Some sites that care about their users (and their users’ eyes) provide ways to switch colors, so if you don’t like the default dark background, you are not forced to watch it. Additionally, there are many ways to override the default colors a site uses but I’d rather visit sites that use readable color schemes than spend my time fine tuning the colors.

Probably I go to extremes, but I will personally never recommend to use a dark background with light font for sites with lot of text to read – I feel this is a usability sin #1. For other types of sites – i.e. image galleries, or even corporate sites where there aren’t 1,000+ word texts, dark backgrounds aren’t a no-no.

Those Tricky Colors That Fit Nowhere

After I discussed the two most common scenarios – i.e. dark on light and light on dark, the only thing left is to discuss all the other color combinations you can think of. These color combinations include the majority of colors but for one reason or another, you can use them neither for background, nor for text color because no matter how masterfully you combine them, either the contrast is low, or the combinations aren’t esthetically pleasing (or both).

Of course, this doesn’t mean these colors are useless. Not at all – they are great for headings, especially with larger font sizes, and for emphasis, as seen from the next examples:

Red 3 (#CD0000) on seashell2 (#EEE5DE)

Blue 4 (#00008B) on cornflowerblue (#6495ED)

Colors have a huge effect on readability. This is why you need to choose them wisely so that they not only create esthetically pleasing combinations but also make it easier for users to read the text. Text is an integral part of any site and we shouldn’t punish visitors for coming to our site by using hard to read color combinations.

March 29 2011


4 Tips and Tricks for more Legible Content

These tips and tricks will help you design more readable content for screen readers.

These tips and tricks will help you design more readable content for screen readers.

Readability & legibility are both areas of interest in accessibility and typographic design, and many resources exist that attempt to define what constitutes well designed copy. In this post, we go over a few commonly overlooked and newer ways to implement more legible type on the web.

1. Add Text-Shadow to Custom Fonts

With a growing number of web fonts to choose from, and new ways to implement custom fonts into sites using CSS instead of Javascript or Flash, it’s becoming increasingly popular to stray from traditional common fonts in exchange for fonts that help define a more unique and consistent brand.

This is great for many reasons, and quite a few font foundries have already begun selling web font licenses making the potential for custom fonts substantial. However, for the time being, there are drawbacks.

Perhaps the most overlooked problem about using these custom fonts is how different devices go about rendering fonts differently. Some devices such as recent Apple computers apply font antialiasing that strongly favors reproducing pixel-perfect letter forms, while other systems (such as Windows computers) render font in a way that favors more legible characters at the cost of non-precise letter forms. In short, this means that fonts look considerably different on Apple and Windows operating systems.

For many common web fonts, this isn’t a big concern. These fonts render well on the web as they are. For newer custom web fonts, this becomes a concern as they will not always render as expected across different devices (or even across different browsers). For instance, take a look at how the Typekit font library renders between different setups:

Browsers that use the default font rendering system implemented in Windows sometimes render custom fonts with seemingly jagged edges.

There seem to be several popular views on this specific inconsistency across browsers and operating systems. Some believe that letterforms should be optimized for legibility, while others prefer an approach where letters are reproduced as they were intended to be displayed. Others suggest that the problem lies with fonts that don’t have proper hinting.

Whatever the case, there is a simple way to create smooth custom fonts in some instances despite font rendering implementations. By simply adding a 1px or greater text shadow, custom fonts will often become much more legible on configurations like Chrome on Windows 7. Take a look at the example below:

In this example, Droid Serif is rendered using no text shadow (top) and a 1px transparent text shadow (below).

This is easily implemented in CSS:

      h1 { /* Your selector */
      	font-family:"Some Custom Font", serif;
        text-shadow:0 0 1px transparent;

        /* Or, if you need to apply a 0px hard shadow,
         * you can use multiple text shadows */
        text-shadow:0 0 0 #f00, 0 0 1px transparent;

In the future, it is likely that this issue will be solved with CSS properties such as font-smoothing, or by browsers implementing their own font rendering engines. For instance, IE9 has made huge improvements to its own font rendering with hardware-acceleration, which makes use of “DirectWrite, ClearType, and sub-pixel positioning to improve font quality and readability“. Until becomes less of an issue, it should be noted that using text-shadows isn’t a fix that works 100% of the time. Some fonts will simply not render well between devices and browsers at all sizes, and should be tested to ensure content can be read effectively (especially in long copy).

2. Use the “text-rendering” CSS property

This is another relatively new way CSS property, with limited browser support. By using the text-rendering property, it is possible to favor rendering speed, legibility, and in the future it should also be possible to emphasize geometric precision of rendered type.

Currently, text-rendering can be used to optimize legibility in Webkit and Firefox 3. By setting the property’s value to “optimizeLegibility”, the user agent will emphasize legibility, sometimes by enabling ligatures, or adjusting kerning in type.

Anthony Kolber has put together a useful demo for seeing how optimizeLegibility affects type at large sizes.

3. Choosing number of words/characters per line

Determining an ideal number of characters per line and accompanying line space is a subject of much debate. While some suggest that 45-75 characters per line is the ideal length, other studies show that longer line lengths can result in faster reading speeds. At the same time, it’s suggested that while longer lines may result in faster reading speeds, users report that they actually prefer shorter line lengths.

Perhaps there really is an ideal number of characters per line and we simply haven’t found it yet (or at least agreed on it), but it’s almost assuredly related to other properties such as line spacing. Line spacing (leading), or line height, determines the height of a line of text. A taller line height means more space between lines.

Line spacing can greatly influence the appearance of large blocks of text.

Depending on the font being used, the size of the font, and other properties, it may be necessary to tweak line-height, but it’s generally accepted that longer lines require more leading. Adjusting the line-height of blocks of text is very simple using CSS:

      p { /* Your selector */
      	line-height:24px; /* This could also use other units such as "em" */

4. Choosing text with appropriate contrast

Choosing appropriate font and background combination colors/brightness is another subject of debate for screen media. A point that is generally agreed upon is that text must meet a minimum contrast ratio in order to be read effectively by a large audience.

According to the Web Content Accessibility Guidelines 2.0 (WCAG20), text should have a minimum contrast ratio of 4.5:1:

A contrast ratio of 3:1 is the minimum level recommended by [ISO-9241-3] and [ANSI-HFES-100-1988] for standard text and vision. The 4.5:1 ratio is used in this provision to account for the loss in contrast that results from moderately low visual acuity, congenital or acquired color deficiencies, or the loss of contrast sensitivity that typically accompanies aging.

Determining the contrast ratio of two colors (text and background color) is easily done with an online tool. Contrast ratio is determined by comparing the relative luminance of the text and background colors.

While these rules imply that higher contrast ratios are ultimately better, some people suggest that too high of contrast actually hurts to read, and use off-white backgrounds, or off-black text instead of 100% black on white. There is however not much quantitative data in this regard. A few sources claim that too much contrast can be difficult for dyslexic readers to view. With these considerations in mind, some designers opt to use #333 instead of #000 (or similar off-blacks) in attempt to make reading more pleasant.

An example of using off-black (#333) text on a white background from the Google Blog.

Useful resources

The Elements of Typographic Style is applauded by many as an incredibly useful resource for graphic and typographic designers. Robert Bringhurst does a wonderful job teaching the fundamentals of typographic style, and much of the information presented in the book can be useful when designing for the web.

WCAG 2.0 provides recommendations for making web content more accessible. While it isn’t exactly loved by everyone, guidelines offered by WCAG still seem to be useful for the most part.

The Effects of Line Length on Reading Online News is a study that examines “the effects of line length on reading speed, comprehension, and user satisfaction of online news articles”. While this is an interesting read, the study only samples twenty college-age students, which could easily not make it relevant for all readers.

December 09 2009


Top 15+ Best Practices for Writing Super Readable Code

Code readability is a universal subject in the world of computer programming. It’s one of the first things we learn as developers. Readable and maintainable code is something to be proud of in a finished product. We can share it with others, contribute to other projects, and reuse code from applications we wrote months or even years ago.

This article will detail the fifteen most important best practices when writing readable code.

1. Commenting & Documentation

IDE’s (Integrated Development Environment) have come a long way in the past few years. This made commenting your code more useful than ever. Following certain standards in your comments allow IDE’s and other tools to utilize them in different ways.

Take this example:

The comments I added at the function definition can be previewed whenever I use that function, even from other files.

Here is another example where I call a function from a third party library:

In these particular examples, the type of commenting (or documentation) used is based on PHPDoc and the IDE is Aptana.

2. Consistent Indentation

I assume you already know that you should indent your code. However, it’s also worth noting that it is a good idea to keep your indentation style consistent.

There are more than one way of indenting code.

Style 1:

function foo() {
	if ($maybe) {
	} else {

Style 2:

function foo()
	if ($maybe)

Style 3:

function foo()
{	if ($maybe)
	{	do_it_now();
	{	abort_mission();

I used to code in style #2 but recently switched to #1. But that is only a matter of preference. There is no “best” style that everyone should be following. Actually, the best style, is a consistent style. If you are part of a team or if you are contributing code to a project, you should follow the existing style that is being used in that project.

The indentation styles are not always completely distinct from each other. Sometimes they mix different rules. For example, in PEAR Coding Standards, the opening bracket “{” goes on the same line as control structures, but they go to the next line after function definitions.

PEAR Style:

function foo()
{                     // placed on the next line
    if ($maybe) {     // placed on the same line
    } else {

Also note that they are using four spaces instead of tabs for indentations.

Here is a Wikipedia article with samples of different indent styles.

3. Avoid Obvious Comments

Commenting the code is great; however, it can be overdone or just be plain redundant. Take this example:

// get the country code
$country_code = get_country_code($_SERVER['REMOTE_ADDR']);

// if country code is US
if ($country_code == 'US') {

	// display the form input for state
	echo form_input_state();

When the text is that obvious, it’s really not productive to repeat it within comments.

If you really must comment on that code, you can just combine it to a single line instead:

// display state selection for US users
$country_code = get_country_code($_SERVER['REMOTE_ADDR']);
if ($country_code == 'US') {
	echo form_input_state();

4. Code Grouping

More often than not, certain tasks take a few lines of code. It is a good idea to keep these tasks within separate blocks of code, with some spaces between them.

Here is a simplified example:

// get list of forums
$forums = array();
$r = mysql_query("SELECT id, name, description FROM forums");
while ($d = mysql_fetch_assoc($r)) {
	$forums []= $d;

// load the templates

Adding a line of comment at the beginning of each block of code also emphasizes the visual separation.

5. Consistent Naming Scheme

PHP itself is sometimes guilty of not following consistent naming schemes:

  • strpos() vs. str_split()
  • imagetypes() vs. image_type_to_extension()

First of all, the names should have word boundaries. There are two popular options:

  • camelCase: First letter of each word is capitalized, except the first word.
  • underscores: Underscores between words, like: mysql_real_escape_string().

Having different options creates a situation similar to the indent styles, as I mentioned earlier. If an existing project follows a certain convention, you should go with that. Also, some language platforms tend to use a certain naming scheme. For instance, in Java, most code will be using camelCase names, while in PHP, most code will use underscores.

These can be also mixed. Some people prefer to use underscores for procedural functions, and class names, but use camelCase for class method names:

class Foo_Bar {

	public function someDummyMethod() {



function procedural_function_name() {


So again, there is no obvious “best” style, besides just being consistent.

6. DRY Principle

DRY stands for Don’t Repeat Yourself. Also known as DIE: Duplication is Evil.

The principle states:

“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”

The purpose for most applications (or computers in general) is to automate repetitive tasks. This principle should be maintained in all code, even web applications. The same piece of code should not be repeated over and over again.

For example, most web applications consist of many pages. It’s highly likely that these pages will contain common elements. Headers and footers are usually best candidates for this. It’s not a good idea to keep copy pasting these headers and footers into every page. Here is Jeffrey Way explaining how to create templates in CodeIgniter.




7. Avoid Deep Nesting

Too many levels of nesting can make code harder to read and follow.

function do_stuff() {

// ...

	if (is_writable($folder)) {

		if ($fp = fopen($file_path,'w')) {

			if ($stuff = get_some_stuff()) {

				if (fwrite($fp,$stuff)) {

					// ...

				} else {
					return false;
			} else {
				return false;
		} else {
			return false;
	} else {
		return false;

For the sake of readability, it is usually possible to make changes to your code to reduce the level of nesting:

function do_stuff() {

// ...

	if (!is_writable($folder)) {
		return false;

	if (!$fp = fopen($file_path,'w')) {
		return false;

	if (!$stuff = get_some_stuff()) {
		return false;

	if (fwrite($fp,$stuff)) {
		// ...
	} else {
		return false;

8. Limit Line Length

Our eyes are more comfortable with reading tall and narrow columns of text. That’s the reason newspaper articles look like this:

It is a good practice to avoid writing very long lines of code.

// bad
$my_email->set_from('')->add_to('')->set_subject('Methods Chained')->set_body('Some long message')->send();

// good
	->set_subject('Methods Chained')
	->set_body('Some long message')

// bad
$query = "SELECT id, username, first_name, last_name, status FROM users LEFT JOIN user_posts USING(, user_posts.user_id) WHERE post_id = '123'";

// good
$query = "SELECT id, username, first_name, last_name, status
	FROM users
	LEFT JOIN user_posts USING(, user_posts.user_id)
	WHERE post_id = '123'";

If you follow the “Avoid Deep Nesting” suggestion, that will also help the line lengths to stay at a reasonable size.

Also, if anyone is going to read the code from a terminal window, such as VI users, it is a good idea to to limit the line length to around 80 characters.

9. File and Folder Organization

Technically, you could write an entire application code into a single file. But that could be a nightmare to read and maintain.

During my first programming projects, I knew about the idea of creating “include files”. However I was still not even remotely organized. I created an “inc” folder, with 2 files in it: db.php and functions.php. As the applications grew, the functions file also became huge and unmaintainable.

One of the best approaches is to either use a framework or imitate their folder structure. Here is what CodeIgniter looks like:

10. Consistent Temporary Names

Normally, the variables should be descriptive and contain one or more words. But, this doesn’t necessarily apply to temporary variables. They can be as short as a single character.

It is a good practice to use consistent names for your temporary variables that have the same kind of role. Here are a few examples that I tend use in my code:

// $i for loop counters
for ($i = 0; $i < 100; $i++) {

	// $j for the nested loop counters
	for ($j = 0; $j < 100; $j++) {


// $ret for return variables
function foo() {
	$ret['bar'] = get_bar();
	$ret['stuff'] = get_stuff();

	return $ret;

// $k and $v in foreach
foreach ($some_array as $k => $v) {


// $q, $r and $d for mysql
$q = "SELECT * FROM table";
$r = mysql_query($q);
while ($d = mysql_fetch_assocr($r)) {


// $fp for file pointers
$fp = fopen('file.txt','w');

11. Capitalize SQL Special Words

Database interaction is a big part of most web applications. If you are writing raw SQL queries, it is a good idea to keep them readable as well.

Even though SQL special words and function names are case insensitive, it is common practice to capitalize them to distinguish them from your table and column names.

SELECT id, username FROM user;

UPDATE user SET last_login = NOW()
WHERE id = '123'

SELECT id, username FROM user u
LEFT JOIN user_address ua ON( = ua.user_id)
WHERE ua.state = 'NY'
ORDER BY u.username
LIMIT 0,20

12. Separation of Code and Data

This is another principle that applies to almost all programming languages in all environments. In the case of web development, the “data” usually implies HTML output.

When PHP first came out many years ago, it was mainly seen as a template engine. It was common to have big HTML files with a few lines of PHP code in between. However, things have changed over the years and websites became more and more dynamic and functional. The code is now a huge part of web applications, and it is no longer a good practice to combine it with the HTML.

You can either apply the principle to your application by yourself, or you can use a third party tool (template engines, frameworks or CMS’s) and follow their conventions.

Popular PHP Frameworks:

Popular Template Engines:

Popular Content Management Systems

13. Alternate Syntax Inside Templates

You may choose not to use a fancy template engine, and just go with plain inline PHP in your template files. This does not necessarily violate the “Separation of Code and Data,” as long as the inline code is directly related to the output, and is readable. In this case you should consider using the alternate syntax for control structures.

Here is an example:

<div class="user_controls">
	<?php if ($user = Current_User::user()): ?>
		Hello, <em><?php echo $user->username; ?></em> <br/>
		<?php echo anchor('logout', 'Logout'); ?>
	<?php else: ?>
		<?php echo anchor('login','Login'); ?> |
		<?php echo anchor('signup', 'Register'); ?>
	<?php endif; ?>

<h1>My Message Board</h1>

<?php foreach($categories as $category): ?>

	<div class="category">

		<h2><?php echo $category->title; ?></h2>

		<?php foreach($category->Forums as $forum): ?>

			<div class="forum">

					<?php echo anchor('forums/'.$forum->id, $forum->title) ?>
					(<?php echo $forum->Threads->count(); ?> threads)

				<div class="description">
					<?php echo $forum->description; ?>


		<?php endforeach; ?>


<?php endforeach; ?>

This lets you avoid lots of curly braces. Also, the code looks and feels similar to the way HTML is structured and indented.

14. Object Oriented vs. Procedural

Object oriented programming can help you create well structured code. But that does not mean you need to abandon procedural programming completely. Actually creating a mix of both styles can be good.

Objects should be used for representing data, usually residing in a database.

class User {

	public $username;
	public $first_name;
	public $last_name;
	public $email;

	public function __construct() {
		// ...

	public function create() {
		// ...

	public function save() {
		// ...

	public function delete() {
		// ...


Procedural functions may be used for specific tasks that can be performed independently.

function capitalize($string) {

	$ret = strtoupper($string[0]);
	$ret .= strtolower(substr($string,1));
	return $ret;


15. Read Open Source Code

Open Source projects are almost always built with collaboration between many developers. These projects need to maintain a good level of code readability so that the team can work together as efficiently as possible. Therefore, it is a good idea to sometimes browse through the source code of these projects to observe what these developers are doing.

16. Code Refactoring

Refactoring means to make changes to the code without changing any of its functionality. You can think of it like a “clean up,” for the sake of improving readability and quality.

This doesn’t include bug fixes or addition of any new functionality. You may refactor code that you have written the day before, while it’s still fresh in your head, so that it is more readable and reusable when you may potentially look at it two months from now. Therefore, usually the motto is: “refactor early, refactor often.”

You may apply any of the “best practices” of code readability during the refactoring process.

I hope you enjoyed this article! Any that I missed? Let me know via the comments.

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
Get rid of the ads (sfw)

Don't be the product, buy the product!