docs

http://docs.nodejitsu.com

community powered rocket-fuel for node.js

docs

We believe in sharing knowledge. So we have assembled this growing collection of node.js how-to articles. These articles range from basic to advanced. They provide relevant code samples and insights into the design and philosophy of node itself.

docs.nodejitsu.com is an open source project and is curated by the Nodejitsu team and friends. If you have articles or ideas that you would like to contribute, we'd very much like to accept your pull request!

Usage

Read Articles, get good at Node.js

Browse /articles/ folder or http://docs.nodejitsu.com

To generate the docs

node bin/generate

To start the docs server

node bin/server

Contribution Guide

coming soon

To add an article:

  • make a directory in topics for your article: mkdir articles/how-to-make-an-article (use only letters and dashes)
  • next write your article: vim articles/how-to-make-an-article/article.md
  • create a metadata with this data: vim articles/how-to-make-an-article/metadata.json

metadata.json

javascript { "title":"What is npm?", "date": "Fri Aug 26 2011 03:08:50 GMT-0700 (PST)", "tags": ["npm", "modules"], "author": "nico", "difficulty": 1 }

Directory Structure

topics/
    article-name/ //url version
        metadata.json
        article.md //file with the real article
        assets/
            ...
    ...

Metadata Format

javascript { "title":"What is npm?", "date": "Fri Aug 26 2011 03:08:50 GMT-0700 (PST)", "tags": ["npm", "modules"], "author": "nico", "difficulty": 1 }

Community node.js articles

PhantomJS: Headless WebKit with JavaScript API

How It Works

PhantomJS is a command-line tool that packs and embeds WebKit. Literally it acts like any other WebKit-based web browser, except that nothing gets displayed to the screen (thus, the term headless). In addition to that, PhantomJS can be controlled or scripted using its JavaScript API.

Invoking PhantomJS is easy:

phantomjs script.js [arguments]

where script.js is the script to be invoked and arguments are the optional parameters for the script.

The simplest PhantomJS script looks like this:

console.log('Hello, world!');phantom.exit();

The directory examples in the source code contains various sample scripts. For more information, see also the Quick Start guide. Furthermore, there are more examples in the Service Integration wiki page on how to consume the data from web services using XML, JSONP, and YQL.

Display twitter status

The following script loads twitter URL for a particular user and extract his recent tweets using CSS selector.

var page = new WebPage();page.onConsoleMessage = function(msg) {    console.log(msg);};page.open(encodeURI("http://mobile.twitter.com/Sencha"), function (status) {    if (status !== "success") {        console.log("Unable to access network");    } else {        page.evaluate(function() {            var list = document.querySelectorAll('span.status');            for (var i = 0; i < list.length; ++i) {                console.log((i + 1) + ": " + list[i].innerHTML.replace(/<.*?>/g, ''));            }        });    }    phantom.exit();});

Find pizza in New York

Here is another example of CSS selector: finding pizza in New York using Google Places. This script would list 10 pizzeria, along with the address and the telephone number.

var page = new WebPage();page.open('http://www.google.com/m/local?site=local&q=pizza+in+new+york', function (status) {    if (status !== 'success') {        console.log('Unable to access network');    } else {        var results = page.evaluate(function() {            var list = document.querySelectorAll('div.bf'), pizza = [], i;            for (i = 0; i < list.length; i++) {                pizza.push(list[i].innerText);            }            return pizza;        });        console.log(results.join('\n'));    }    phantom.exit();});

Get approximate location

This ipgeocode.js script shows the approximated location based on the network IP address, using freegeoip JSONP API.

var cb = function (data) {    var loc = data.city;    if (data.region_name.length > 0)        loc = loc + ', ' + data.region_name;    console.log('IP address: ' + data.ip);    console.log('Estimated location: ' + loc);    phantom.exit();};var el = document.createElement('script');el.src = 'http://freegeoip.net/json/?callback=cb';document.body.appendChild(el);

Example output:

> phantomjs ipgeocode.js
IP address: 75.25.137.196
Estimated location: Palo Alto, California

For testing legacy applications

10 Papers Every Programmer Should Read (At Least Twice)

10 Papers Every Programmer Should Read (At Least Twice) 525

Posted by Michael Feathers on Friday, February 27, 2009

I spent most of yesterday afternoon working on a paper I’m co-writing. It was one of those days when the writing came easy. I was moving from topic to topic, but then I realized that I was reaching too far backward – I was explaining things which I shouldn’t have had to explain to the audience I was trying to reach.

When I first started writing, one of the pieces of advice that I heard was that you should always imagine that you are writing to a particular person. It gets your juices going – you’re automatically in an explanatory state of mind and you know what you can expect from your audience. I was doing that, but I noticed that I was drifting. I was losing my sense of audience. I started to explain one thing, and then I realized that I would have to explain something else to help it make sense. I couldn’t imagine that person any more. How could I know what they know and what they don’t?

The problem I was experiencing is only getting worse. People come into programming from many different directions. Some started in other fields, and others started programming as teens. Some started with BASIC, others started with Ruby or C. The industry is filled with knowledge, but it isn’t common knowledge. It isn’t knowledge that we all share. We have to dig for it because of a peculiar fact about our industry: we reinvent our languages and notations every ten years. It’s hard to find deeply technical books and articles which stand the test of time in software: they are all Latin within 20 years.

So, I was thinking about this and trying to not to get too glum. I realized that instead of complaining, I could help by pointing to some papers which are easily available online and which (to me at least) point to some of the most interesting ideas about software. To me, these are classic papers which contain deep “things you oughta know” about code – the material you work with.

We’ve taken an interesting turn in the industry over the past ten years. We’ve come to value experiential learning much more, and we’ve regained a strong pragmatic focus, but I think it would be a shame if we lost sight of some of the deeper things which people have learned over the past 50 years. Rediscovering them would be painful, and (to me) not knowing them would be a shame.

Here’s the original list. It’s a rather personal list of foundational papers and papers with deep ideas. I wrote it “off the cuff” and threw it into a tumblr blog the other day and I got responses from people who suggested others. I’ll add those in a later blog.

Most are easy to read but some are rough going – they drop off into math after the first few pages. Take the math to tolerance and then move on. The ideas are the important thing.

  1. On the criteria to be used in decomposing systems into modules – David Parnas
  2. A Note On Distributed Computing – Jim Waldo, Geoff Wyant, Ann Wollrath, Sam Kendall
  3. The Next 700 Programming Languages – P. J. Landin
  4. Can Programming Be Liberated from the von Neumann Style? – John Backus
  5. Reflections on Trusting Trust – Ken Thompson
  6. Lisp: Good News, Bad News, How to Win Big – Richard Gabriel
  7. An experimental evaluation of the assumption of independence in multiversion programming – John Knight and Nancy Leveson
  8. Arguments and Results – James Noble
  9. A Laboratory For Teaching Object-Oriented Thinking – Kent Beck, Ward Cunningham
  10. Programming as an Experience: the inspiration for Self – David Ungar, Randall B. Smith

(edit: Added a brief synopsis of each of them and why I think they are special):

On the criteria to be used in decomposing systems into modules – Parnas

This is a very old paper, but it is more than a classic. In in it, Parnas introduces a forerunner to the Single Responsibility Principle. He introduces the idea that we should use modularity to hide design decisions – things which could change. People still don’t consider this as often as they should.

Another thing I really like in the paper is his comment on the KWIC system which he used as an example. He mentioned that it would take a good programmer a week or two to code. Today, it would take practically no time at all. Thumbs up for improved skills and better tools. We have made progress.

A Note On Distributed Computing – Waldo, Wyant, Wollrath, Kendall

Abstraction is great but it can only go so far. In this paper, the authors lay to rest what was once a pervasive myth – that we could design a distributed system and make distribution transparent. Ever wonder why you had to implement specific interfaces to do remoting in Java? This is why.

In the aftermath it might seem hard to believe that people thought this was possible. I think we can we partially thank this paper for that.

The Next 700 Programming Languages – Landin

Most of us have spent a lot of time working in traditional programming languages, but functional programming languages are slowly seeing an uptick and many OO languages are gaining functional features. This paper (which reads like a tutorial) makes an argument for an expression-oriented style of programming. It also lays the foundation for lazy evaluation.

One of the other neat things about this paper, from a historical point of view, is that there is a discussion section at the end in which there a number of questions and comments about whether making indentation significant in a language is a good idea. I was thrown to see people asking whether or not this would be a problem for functions which span over several pages(!).

Can Programming Be Liberated from the von Neumann Style? – Backus

John Backus is known for a number of achievements in computer science. He received the ACM Turing Award for his work on Fortran. This paper, which he presented at the award ceremony was rather shocking at the time because it said, in essence, “we got it wrong.” Backus took the opportunity to make a plea for pure functional programming. His arguments were convincing and they helped to set a research agenda which is just now starting to make some waves in the mainstream.

Reflections on Trusting Trust – Thompson

I once heard that when this paper was presented, people in attendance rushed back to de-compile their C compilers and look for, er, problems. This paper unveiled a hard problem at the heart of computer security. If you’ve spent any time at all thinking about security, you need to read it.

Lisp: Good News, Bad News, How to Win Big – Gabriel

This paper is a bit atypical in this list. It’s aimed at the Lisp community and it comes off as a bit of a lament. But, hidden deep within it is the Gabriel’s description of the ‘Worse is Better’ philosophy – an idea with profound implications for the acceptance and spread of technology.

An experimental evaluation of the assumption of independence in multiversion programming – John Knight and Nancy Leveson

Behind this dry title lies something very interesting. I first heard about this paper from Ralph Johnson in a newsgroup discussion about program correctness. It turns out that one of the avenues that engineers in other disciplines take to make their products stronger – redundancy – doesn’t really work in software. Multi-version programming was the idea that you could decrease faults in critical systems by handing the spec to several teams, having them develop the software independently, and then having the systems run in parallel. A monitoring process verifies their results and if there is any discrepancy it picks the most common result. Sounds like it should work, right? Well..

Arguments and Results – Noble

I think that all of the other papers in this list are rather well known in some circles. This one isn’t, or if it is, I just haven’t found that circle yet. What I like about this paper is that it takes something which we deal with every day – the set of arguments and results of functions – and it works them through a series of variations which just don’t occur to many people. The fact is, every function that you work with has a number of possible directions if could evolve in. Not all of them are appropriate, but if you know the possible directions, you’re richer for it.

A Laboratory For Teaching Object-Oriented Thinking – Beck, Cunningham

There are an incredible number of papers about there about object orientation. The thing which makes this one great is its directness. OO went through a number of stages. It was once fresh and novel, then it was ornate, and then it became matter-of-fact. This paper hits upon key ideas which many people don’t talk about much any more: anthropomorphism and dropping the top/down perspective. It also shows you how you can design with index cards. It may not sound cool but it is incredibly effective.

Programming as an Experience: the inspiration for Self – Ungar, Smith

How many people know about the Self Project? Not enough in my opinion. Self was an attempt to take two ideas in computing and push them as far as humanly possible. The first was minimalism: the Self programming language was thoroughly in the Lisp and Smalltalk vein – everything was defined in terms of the smallest number of primitives possible. The other idea was direct manipulation – the idea that the object metaphor could be pushed all the way in the user interface – the programmer and user sit with a mouse in a sea of directly clickable objects and use them for everything. If they could’ve gotten away with dropping the keyboard, I think they would’ve.

The amount of technology which the Self project threw off is terrifying also. Self broke ground in dynamic language optimization and VM design. Chances are, your VM uses technology it pioneered. It’s also one of the more perverse ironies that the most widely distributed programming language today (JavaScript) is a prototype-based programming language which borrowed ideas from the hyper-research-y Self.

What would you add to the list?

I should read these at least once!

MoonScript, a language that compiles to Lua

Overview of Differences & Highlights

A more detailed overview of the syntax can be found in the documentation.

  • Whitespace sensitive blocks defined by indenting
  • All variable declarations are local by default
  • export keyword to declare global variables, import keyword to make local copies of values from a table
  • Parentheses are optional for function calls, similar to Ruby
  • Fat arrow, =>, can be used to create a function with a self argument
  • @ can be prefixed in front of a name to refer to that name in self
  • ! operator can be used to call a function with no arguments
  • Implicit return on functions based on the type of last statement
  • : is used to separate key and value in table literals instead of =
  • Newlines can be used as table literal entry delimiters in addition to ,
  • \ is used to call a method on an object instead of :
  • +=, -=, /=, *=, %= operators
  • != is an alias for ~=
  • Table comprehensions, with convenient slicing and iterator syntax
  • Lines can be decorated with for loops and if statements at the end of the line
  • If statements can be used as expressions
  • Class system with inheritance based on metatable’s __index property
  • Constructor arguments can begin with @ to cause them to automatically be assigned to the object
  • Magic super function which maps to super class method of same name in a class method
  • with statement lets you access anonymous object with short syntax

Serious programming languages have alternative languages that compile.

Programming Achievements: How to Level Up as a Developer

Programming Achievements: How to Level Up as a Developer

Published on Tuesday, August 09, 2011 in better

How does a good developer become a great developer?

Forget greatness for a moment: How does a decent developer become a good developer?

There is no definitive path from Step 1 to Step n. Heck, it's not even clear what Step n is. And as logically-minded developer types, the lack of a well-defined route can make for a daunting journey from novice to master.

I've spent a fair bit of time over the last few years bumping up against this conundrum. What's next? How do I go from being a good developer to a being really good developer?

What Does Success Look Like?

I do my best work when I have a goal with clear, measurable criteria for success. For example, I want to run a 5-minute mile. Okay. That's easy to measure, and success is well-defined. I can figure out how fast I can run a mile now, and the Web is full of advice and training programs for getting faster. I can choose a training program, work hard, and I can be confident that I'll eventually get where I want to be. And it's so wonderfully measurable that, every week, I'll know just how close I am to my ultimate goal.

But how do you measure whether you've attained the rank of "really good developer?" In short, you can't. That goal, as stated, is too subjective, too vague, and is simply not measurable. So how do we find something that is measurable?

Much like the goal of wanting to run a 5-minute mile, we can start by looking at where we are as a programmer versus where we want to be. What experiences has a 5-minute-mile runner exposed himself to that a 10-minute-mile runner is lacking? What experiences has the master programmer benefited from that the novice programmer is missing? It's the experiences that matter.

We've all had specific experiences that clearly advanced our skills as developers. We've learned a new language that exposed us to a new way of thinking. Or we crafted the perfect design, only to watch it unveil its gross imperfections in the harsh realities of a production environment. And we became better programmers because of it. Some experiences equip you with new techniques. Others expose you to anti-patterns...and allow you to understand why they are anti-patterns. It's these experiences that teach you, that influence your thought process, that influence your approach to problems, that improve your designs. And conveniently, it's simple to measure whether you've gained a particular experience. (It might be fun to think of them as achievements.)

So it took a while, but I'm becoming more comfortable with the immeasurability of my pending goal: earning the rank of "really good developer." If such a developer earns this distinction because of his experiences, then maybe we can still have a well-defined path marching in the general direction of "really good developer" and beyond. I suspect that path looks something like this:

  1. Identify the experiences that advance a person as a developer.
  2. Select a particular experience to pursue.
  3. Pursue that experience to completion. (Achievement unlocked!)
  4. Reflect on that experience. Really soak it in. [A]
  5. Return to Step 2, this time selecting a new experience.

And what better way to get started with Step 1 than to crowdsource it? Here's a first cut at a list of programming achievements, loosely organized into groups. [B] I'll offer multiple ways for you to chime in with your thoughts at the end.

Achievements

Programming Achievement Badges (by Michael Parenteau)

Learn a variety of programming paradigms:

  • Write a program in assembly language
  • Write an application in a functional language
  • Write an application in an object-oriented language
  • Write an application in a prototype-based language
  • Write an application in a logic programming language
  • Write an application using the Actor model
  • Write an application in Forth [C]

Experience the ins and outs of programming for different platforms:

  • Write a nontrivial web app
  • Write a nontrivial desktop app
  • Write a nontrivial mobile app
  • Write an embedded app
  • Write a realtime system

Enhance your understanding of the building blocks that we use as developers:

  • Write a networking client (e.g., HTTP, FTP)
  • Write a device driver
  • Write a B-tree database
  • Wrap an existing library to provide a better (more pleasant) user experience
  • Write an application or framework that provides a plugin model
  • Write a testing framework
  • Write a programming language

Enlighten yourself with koans, katas, and the wisdom of ages:

Program in the open:

  • Contribute to an open source project
  • Have a patch accepted
  • Earn commit rights on a significant open source project
  • Publish an open source project
  • Perform a Refactotum of an open source project

Learn by teaching others [D]:

  • Present a lightning talk
  • Present at a local user group
  • Present at a conference
  • Deliver a training course
  • Publish a tutorial
  • Publish a constructive code review of an open source project
  • Write a programming book

About the Achievements

Now, let's go meta for a moment. Note that each of these achievements is measurable. Each one is Boolean: you've either completed it or you haven't. For example, it's hard to measure whether you've learned a functional language, but it's easy to know whether you've written an app in a functional language. The latter is observable. Measurable. Boolean. This measurability applies, quite intentionally, to all of these achievements.

Admittedly, the measurability isn't perfect. Consider the achievement of presenting at a conference: you could certainly do a half-assed job just to say you've earned this achievement. But if you're reading this post, I assume you want to be excellent. You know that it's lame to phone it in just to cross an item off the list.

Since We're Talking About Improvement ...

Since we're talking about improvement, what would you change about this list?

The list is available as a gist on GitHub. Feel free to fork it and add more achievements. (Make sure they're measurable.)

Or, fork it and mark off the achievements you've already conquered. You might even flag the one that you're currently working on. (For example, check out these forks from Justin Blake, Pierre Chapuis, and Yann Esposito.)

Or just sound off in the comments: What experiences have made you a better developer? And what achievement will you unlock next?

Notes

[A] I can't emphasize Step 4 enough. To get the most out of each achievement, you owe it to yourself to pause and reflect on the experience before you move on to the next one. Introspect. Ask yourself what you learned. Take the time to write down those thoughts. And even better still, share them with someone else and see how your learnings compare to other people who've also earned this achievement.

[B] It's interesting to see some aspect of this achievement-based model at work on coderwall.com.

[C] Forth is essentially its own paradigm.

[D] This quote comes to mind: "Whoever teaches learns in the act of teaching ..." — Paulo Freire

Updated 8/9/2011 4:32pm UTC - Added links to example forks of the achievement list.

--

Thanks to Michael Parenteau for providing the artwork for this post.

Thanks to Michael Nygard, Glenn Vanderburg, Alan Dipert, and Vojtech Rinik for providing feedback on drafts of this post.

This is an excellent list of programmer "to-dos"

Designing command-line interfaces

There are few articles on the design of command-line interfaces (CLIs), even if plenty of articles on designing graphical user interfaces (GUIs) exist. This article is an attempt at presenting some of the most important guidelines for CLI design.

The article assumes the command-line utilities are to be used on a *nix system (e.g. GNU/Linux, BSD, Mac OS X, Unix), and it will frequently reference to common tools on such systems.

Types of command-line interfaces

There are three major sorts of command-line interfaces:

  • Non-interactive
  • Interactive, line-based
  • Text-based user interface

Non-interactive programs don’t need any user interaction after invocation. Examples include ls, mv and cp.

Interactive, line-based programs are programs that often need interaction from the user during execution. They can write text to standard output, and may request input from the user via standard input. Examples include ed and metasploit.

Text-based user interfaces are a cross between a GUI and a CLI. They are graphical user interfaces running inside a terminal emulator. Examples include nethack and vi. Many (but not all) text-based user interfaces on *nix use either curses or the newer ncurses.

Non-interactive programs get the most attention in this article, while text-based user interfaces are barely covered at all.

Advantages of command-line interfaces

Why use command-line interfaces in the 21st century? Graphical user interfaces were invented decades ago!

Many command-line interfaces provide several advantages over graphical user interfaces, still today. They are mostly popular among power users, programmers and system administrators; partly because many of the advantages apply to their tastes well:

  • Ease of automation: Most command-line interfaces can easily be automated using scripts.
  • Fast startup times: Most command-line interfaces beat their graphical counterparts several times at startup time
  • Easier to use remotely: Maybe it’s just me, but I prefer to remotely control computers via SSH over VNC
  • Lower system requirements: The lower system requirements make CLIs useful on embedded systems.
  • Higher efficiency: Being able to do a lot by just typing some characters instead of searching in menus increases the efficiency which you are able to do work at
  • Keyboard friendly: Grabbing the mouse is a distraction

Disadvantages of command-line interfaces

Having covered the advantages of command-line interfaces, it would be a good idea to also cover the disadvantages of them. The most major disadvantage is that the learning curve is steeper. You will also have to check the manual in many cases, while in a GUI, you can figure out many more things while using the product.

GUIs also have the advantage when it comes to presenting and editing information that is by nature graphical. This includes photo manipulation and watching movies (I have always wanted a program that shows a movie in my terminal by converting it to ASCII art in real-time, that would be sweet).

Try to avoid interactivity

Interactive interfaces are harder to automate than non-interactive user interfaces. The ease of automation is one of the greatest advantages of command-line interfaces, and by making your utility interactive, you give away much of that advantage.

There will be cases when an interactive utility makes more sense than a non-interactive one, but at least don’t make a utility interactive when the advantages are dubious. You shouldn’t create a utility which just asks (interactively) for stuff that could be easily sent to the program as arguments (imagine mv asking you for a source and destination path interactively).

Naming your utility

I would like to stress on the importance of a good name for each command-line utility. This is because a bad name is easy to forget, meaning that users will have to spend more time looking it up.

The name should be short. A long name will be tedious to type, so don’t call you version control program my-awesome-version-control-program. Call it something short, such as avc (Awesome Version Control).

The name should be easy to remember. Don’t call your utility ytzxzy.

Arguments

A lot can be said about the arguments to give to programs. First of all, follow standard practice; single-letter options are prefixed with a hyphen, and multiple of them may follow directly (e.g. -la is the same as -l -a). Multi-letter options start with two hyphens, and each such argument must be separated with spaces. Look at the arguments you give to ls, or cp. Follow the way those work. Examples of commands following non-standard practice include dd, which has been criticized for that, many times.

Continuing on the theme of standard practice, if a similar tool to yours (or a tool in the same category, such as file management) uses some option for some thing, it could be a good idea to copy that behaviour to your program. Look at most *nix file management utilities such as mv, cp and rm. All of these provide a flag called -i, with the same behaviour; asking the user interactively to confirm an action. They also provide a -f flag, to force actions (some of which the computer would think seem stupid, but you know what you are doing while using that option, don’t you?).

Options should be optional. That is part of the meaning of the word, but sometimes it is forgotten. Command-line utilities should be callable with zero, nil and no options at all. Examples include cd, calling it with no arguments returns you to the home directory. Some programs might not make sense to call with no arguments, such as mv, but in many cases, you can find some sensible standard behaviour (remember that it is, however, better to just print an error and exit than to do something stupid the user would never expect to happen (“Oh, you gave rm no options, better remove every file on your disk, just to be sure that the file you wanted to remove gets removed”)).

In the *nix world, there’s a practice that anything after double-hyphens -- should be read as a filename, even if the name contains hyphens (e.g. cmd -- -FILE-). If the arguments list ends with a single-hyphen, input should be read from standard input.

Be careful using many flags whose only difference is the case (e.g. -R and -r), as it will be hard to remember.

Always provide a long form of short arguments. Don’t provide just -i, provide --interactive as well.

Provide --version and --help

There are two options you should always include in your program: --version and --help. The first one should print version information for the program. The second should tell one what the program is for, how to use it and present common, if not all, options.

Reading the input

Make sure your program can read input from pipes, and through file redirection.

If the name of a file is passed as an argument, read the file and use its contents as input. If no such argument was passed, read from standard input until a CTRL+D key sequence is sent.

Silence trumps noise

If a program has nothing of importance to say, then be quiet (the same applies to human beings). When I run mv, I don’t want it to tell me that it moved a file to some other location. After all, isn’t that what I asked it to do? It should come to me as no surprise that that happened, so I don’t need to be told that explicitly. When things you don’t expect to happen do happen, then should you break the silence. Examples include, the file I wanted to move didn’t exist, or I didn’t have permissions to write to the directory I tried to move the file to.

Note that your program don’t need to tell its version or copyright information during each invocation, or print the names of the authors, either. That’s just extra noise, wasting space, bandwidth during remote sessions and possibly making the output harder to automatically process, for instance by sending it to another program through a pipe.

Don’t tell me what the output is, either. One should know what the program they use do. whoami prints the name of the current user, and only the name. If it printed The name of the current user is: x instead of just x, much more work would be involved in extracting just the name.

Most programs provide -v (verbose) options making the program more verbose, and a -q (quiet) option, making the program shut up all together (except possibly for some fatal error). The default behaviour should not be completely silent in every case, but in most cases. Programs that print something should only print what is relevant.

How to ask users for a yes or a no

At times, your programs might need to ask a user for a yes or a no, for different reasons, the most common being confirmations (“do you really want to do this?”). Others could be problems that the computer may offer to fix (“Table USERS doesn’t exist, do you want me to create it for you?”).

While asking for questions requiring either a yes or a no (or a y of an n), you should put (y/n) after the question:

Do you really want to do this (y/n)?

Most programs require you to manually hit return after typing the letter. While this might seem superfluous, most programs do this, and your program should require user to do this as well in order to be consistent and not surprise anyone.

Tell me what kind of input you want, and how you want it

If your program asks for a date, and it doesn’t tell me how I should type that date, I will be confused:

Enter a date:

Tell me the format in which I should input the date, and the confusion is gone:

Enter a date (YYYY-MM-DD):

Likewise, if the program just asks for a length, I would be confused. In kilometers, meters, miles, feet…? When different units for things exist, tell me the unit.

Every program should do one, and only one thing, and do it well

The above heading is one of the most important parts of the Unix philosophy, and it has survived the test of time, being just as solid advice as it was back in the late 1960′s/early 1970′s. In practice, this means that you shouldn’t create a file management program, instead, you should create a program for removing files, another for moving them and another for copying them.

Doing one thing well is partly a side-effect of doing only one thing, which allows greater focus.

  RedditDZoneDiggDeliciousSlashdotMore

The *NIX philosophy, with a nice explanation.