February 14, 2010

Flying over the Rockies

As I write this, I’m in a 737 flying over the Rocky mountains on my way home from a long week in Denver, Colorado. When you think about all the infrastructure that is in place to facilitate a flight from one US city to another it boggles the mind. Not just software and hardware; but people, places, processes, and protocols. With all those puzzle pieces a person and their belongings can be safely (and magically) transported. (I’m hoping :)

All those balls in the air makes me think of the conglomeration of technologies that make up the web services I’ve built and how they are working together to synergistically create an experience and a working model of something much bigger than it’s parts.

Nowadays when a person looks at a website they rarely see a collection of pages but most websites have become their own platform and environment for the user. The advent of Ajax and frameworks like jQuery, have made a consistent look and feel with consistent user controls a must have for any (aspiring) mainstream site.

To extend my (overextended) flying analogy, certain plane manufacturers and boarding methods for example have become the default choice for all airlines. This is generally a good thing. We want our planes to be Boeing and our airports to have rolling sidewalks. (Those are awesome by the way; “Look at me! I’m walking and I’m not moving my legs!”).

However along the way it seems we’ve laid aside some important considerations on the merits of a completely unobtrusive (read “it doesn’t get in my way”), user interface.

Remember standard hyperlinks? Why do away with a method that has worked for years just because you can slap an id an on element and a write up a jQuery function? We need to at least with temerity consider not breaking a time tested model.

Remember documentation that was simple text pages hyperlinked together? An amazing tool still today which many have abandoned.

If you’ve created an exclusive club that requires an up to the minute javascript interpreter, at least bother to preserve the use of the old fashioned back button.

It so easy to ignore all the technologies that, when built upon, gave us our new shiny toys. However it takes much more effort to see the important parts of those base UI features that would be catastrophic (in a “your new app sucks” kind of way) to leave behind.

January 20, 2010

Conjunction Junction What’s your Function

Today I’ve decided to go over functions, (also known as “methods” or “subroutines”) the building blocks of modular code; and show why it’s a good idea to use them in your programming.

When I first started writing web applications I didn’t really understand what a function was and how it worked, so I just avoided them. I would instead write something procedurally and if I needed to do the same thing over again I would repeat that line (or lines) of code again.

Doing this breaks one of the important ethos of programming called DRY (“Don’t Repeat Yourself”). In a program of any sufficient complexity, repetition of code is NOT your friend.

Let me demonstrate how using a function can save you from repeating lines of code over and over.

Here is a section of PHP code that calculates a human readable string of days, hours, minutes, and seconds from two times to give a files age. I want to get the plurals of day(s), hour(s), etc., correct. So I am testing the number to see if there is more than one and adding an “s” to the end if there is.

<?php
//...
$seconds = strtotime($curdate) - strtotime($olddate);
/*** number of days ***/
$days=(int)($seconds/86400);
/*** number of hours ***/
$hours = (int)(($seconds-($days*86400))/3600);
/*** number of mins ***/
$mins = (int)(($seconds-$days*86400-$hours*3600)/60);
/*** number of seconds ***/
$secs = (int)($seconds - ($days*86400)-($hours*3600)-($mins*60));
/*** return the string ***/
if($days != 0) {
	if($days > 1) {
		$plural = "s ";
	} else {
		$plural = " ";
	}
	$file_age = $days . " day" . $plural;
}
if($hours != 0) {
	if($hours > 1) {
		$plural = "s ";
	} else {
		$plural = " ";
	}
	$file_age .= $hours . " hr" . $plural;
}
if($mins != 0) {
	if($mins > 1) {
		$plural = "s ";
	} else {
		$plural = " ";
	}
	$file_age .= $mins . " min" . $plural;
}
if($secs != 0) {
	if($secs > 1) {
		$plural = "s ";
	} else {
		$plural = " ";
	}
	$file_age .= $secs . " sec" . $plural;
}
echo $file_age;
//...
?>

Using a function to simplify the getting of the plural distills the 20+ lines of code into one function making it in essence 5 lines of code.

<?php
//...
function getPlural($num) {
        /*** if more than one ***/
        if($num > 1) {
                $plural = "s ";
        } else {
                $plural = " ";
        }
        return $plural;
}

function calculateFileAge($curdate, $olddate) {
	/*** get difference in times in seconds ***/
	$seconds = strtotime($curdate) - strtotime($olddate);
	/*** number of days ***/
	$days=(int)($seconds/86400);
	/*** number of hours ***/
	$hours = (int)(($seconds-($days*86400))/3600);
	/*** number of mins ***/
	$mins = (int)(($seconds-$days*86400-$hours*3600)/60);
	/*** number of seconds ***/
	$secs = (int)($seconds - ($days*86400)-($hours*3600)-($mins*60));
	/*** return the string ***/
	if($days != 0) {
		$file_age = $days . " day" . getPlural($days);
	}
	if($hours != 0) {
		$file_age .= $hours . " hr" . getPlural($hours);
	}
	if($mins != 0) {
		$file_age .= $mins . " min" . getPlural($mins);
	}
	if($secs != 0) {
		$file_age .= $secs . " sec" . getPlural($secs);
	}
	return $file_age;
}
//...
?>

This function called getPlural() is a very simple function we pass the function one “argument” (one independent variable that is the input to a function). In our case that argument is the $num variable. In the function definition (where we define function getPlural()), $num is just a placeholder for whatever variable we input. In the example we input to the function a number of days, hours, minutes, and seconds.

The function does the work of examining the number and then returning a single variable that either is “s” or an empty string.

The nice thing about designing a function is that once your function does it’s job; namely taking arguments and returning a result. It is a nice black box which you don’t have to think about how it operates any more and you can use it over and over again without repeating the code that is contained therein.

Functions are a great tool for helping you to stay original and stop repeating yourself.

November 28, 2009

Following Twitter from the Command Line

Previously I showed you how to tweet from the command line. It’s even easier to follow your twitter network from the command line.

#!/bin/bash

user=twitteruser
pass=twitterpass

curl -s -u ${user}:${pass} 'http://twitter.com/statuses/friends_timeline.xml?count=30' | xmlstarlet sel -t -m '//status' -v 'user/screen_name' -o ': ' -v 'text' -n

This will show you the last 30 tweets in your friends timelines combined. You can adjust the count to show more or less. Having cUrl and xmlstarlet (a command line XML/XSLT toolkit) installed (and having a bash environment) is a prerequisite.

August 29, 2009

An Open Invitation to the Programming Profession

code2Many of you may not believe me when I tell you that programming is within the grasp of the layman. Maybe you’re one of those people who, when you see a screen full of code, your mind just shuts down and goes blank. Well I’m here to tell you that the tools available to master programmers are available to you for just a few weekly payments of an hour. It will take your time in complete mental focus. I won’t be one to tell you that you can Learn PHP in 24 Hours or 10 minutes to learn PERL, as the books intimate. But, with a solid investment of your time you WILL reap the rewards of time savings from the efficiencies gained with your programming. Custom computer programs are no longer the sole domain of a team of programmers or a hermited mole-like technophile. You can easily build a programming environment in an afternoon and be mucking with variables, looping structures, and logical operators that same day. Like any endeavor it will take years of effort to be a master. Let me explain a few things to the uninitiated about programming that you may not know. Simple things that reveal how programming is done in this day and age.

A few simple truths about programs and code:

Common code is stored in plain text files


You may not be familiar with plain text files. They don’t offer much to the layman, but to the programmer they are the keys to the kingdom. For todays popular languages all start with their source code being typed into a plain text file. It may be renamed to not have the “.txt” extension, but it is still plain text. Word documents (.doc) ARE NOT plain text files. Think “notepad” if you are a Windows user. Plain text files do not have formatting, the raw stored type is just text.

Code is edited with plain text editors


Source code is typed into those text files using simple text editors. Now many complicated IDE’s are used but for the beginner a simple no-nonsense plain text editor will be the best for learning. It won’t trip you up if you completely comprehend your simple text editor. Once you know what you’re doing, learn a real text editor.

Syntax is crucial


When you’re typing a letter to your mom, she might not mind if you misspell a few words or miss a punctuation point here or there. However programs require you to be nearly 100% accurate. The compiler or intrepreter, the part of the computer that figures out what you want from your program, is very picky. It may always want a semi-colon after each line. It may want indenting to be a certain number of characters. It may differentiate between upper case and lower case. The kind of bracket you use might matter. You must learn the language. Programming languages however are much easier to learn than the spoken kind. For one thing the number of terms in a programming language is much lower. Pay attention to syntax (How you type the program in).

Know your environment first


I mentioned above about building your own programming environment. Sure you can just program using web-based platforms or on remote servers, but if you didn’t set it up you will continue for some time to struggle with the question of “Is this problem my code or my setup of the programming environment?” So not only should you go through the basic programming tutorials for your language of choice, you should also follow tutorials on setting up your environment. Whether it’s PHP, Python, Perl, or Prolog (or some other language not starting with “p”) it helps you to know how things are installed and configured. As a beginning programmer you will see error messages, and your job will be to continue hacking at the code until errors are abated.

Persistence is paramount


If you do not have the willingness to persist when a problem gets tough, you will fail. You will fall short of your goal you are trying to achieve. This holds true for any endeavor in life, and no less in the task of a programmer. Remember that when you’re up against a wall and you can’t figure out a problem. Take a break. Come back at it from another angle. Keep doing it until it’s done. You will learn and grow and improve if you just don’t give up.