Empty your bladder before watching movie

Toilet sign What does emptying your bladder before watching movies have anything to do with software development? Read on to find out… Before that, I want to tell you a story… and no, it doesn’t start with “Once upon a time”…

The movie afternoon

It was a beautiful Saturday afternoon. I had just taken my lunch and on a whim, decided to watch a movie. Glancing through the available movies, I thought “Bee Movie” seemed interesting. So I got my tickets and went in punctually.

Well, I don’t know how movies are aired in other countries, but in Singapore, there’s a 10 minute segment where commercials and movie trailers are aired before the actual movie is shown. There’s a comfortable seat waiting for me and there’s air conditioning (believe me, in Singapore, low temperatures are a premium), so I usually just go in to the movie theatre early and rest up. Besides, I get to view new movie trailers and sometimes, the commercials are funny or inventive or creative.

Anyway, I was already comfortably slumped in my seat and this lady and her maid towing two children came along. They were sitting in my row, so I shifted slightly to let them pass and they sat down. Since it’s still within that 10 minute segment, the lady asked one of her children that he go to the toilet now. Then she promptly dragged that boy out. Unsurprisingly, I’ve got to move again to let them out.

After a few minutes, they came back, just in time for the movie, and again, I’ve got to move to let them in.

This situation is actually very common. Parents do that. And couples. And large groups of teenagers. Anytime there’s more than one person in the movie watching group, this situation potentially comes up.

These people come in, sit down, and after like 1 minute, decide that they need to go to the toilet, or buy a hot dog, or get a drink. Wouldn’t they have thought of those errands before they come in to the theatre?

There’s only one answer: laziness.

Movie watching is a fairly common activity. You probably did it quite a few times. Is it very difficult to foresee that you want to go to the toilet or buy that hot dog and drink beforehand?

They just had to come in and check that they still have time before the actual movie starts. Then they run out like there’s no tomorrow and do whatever they need to do, and feel like oh, they’ve gotten one thing down pat.

This is not about getting things done. It’s not even a productivity issue. It’s an issue of poor planning. Do you really think coming all the way in to the theatre, sit down and then running out again to do mini errands is efficient?

The software development parallel

Just like there are tasks you can foresee for movie watching, there are tasks you can foresee for software development. Design, thinking, business logic understanding. Preparation. All before writing a single line of code.

You don’t rush in to write a fantastic code base, and then find out that “oh, maybe I should’ve thought of that…” and then rewrite your entire code base to incorporate a business logic that should have already been thought out.

You don’t rush in to write code for web pages, and then find out that “oh, if I generalise this part, it can be used as a template for other web pages as well”.

Design first. Think first. Prepare first. It doesn’t take a lot of time, and you know you should do it. So why don’t you? Laziness. It’s much easier to fall into the trap of coding to feel productive. I’ve sometimes fallen for this trap too, and it’s usually undone a lot of my work.

Just as some movies aren’t bladder friendly, some software projects aren’t design friendly either. These projects are either too complex or too simple. Complexity intimidates your mind, and you feel it’s too much work to think things through. Simplicity fools your mind, and you feel anything more than “I just code this, and code that, and everything’s done” is too much thinking.

Even a short period of designing and planning can do wonders for a software project. It’s saved my skin at least once, because of the short deadline given.

So how do you start your software development projects?

Multi-sensory input in artificial intelligence

Robot playing chess Artificial intelligence has always been one of my favourite topics of interest. Artificial intelligence or AI, as it’s commonly known, is

the study and design of intelligent agents where an intelligent agent is a system that perceives its environment and takes actions which maximizes its chances of success.

I think of AI more in terms of simulation. How can a certain behaviour be simulated? How can a certain phenomena be simulated? For example, flock behaviour can be simulated using simple rules yet resulting in complex patterns. I’ve even tried my hand at computer virus simulations.

There was a time when I was into game development. I mean, like really into it. I joined an independent game development group. Can’t remember from where (I think I found the group from GameDev). Can’t remember the group name too (I think it has a “rhino” somewhere…)

Anyway, there wasn’t much documentation yet, except that it’s a “get the flag” kind of game (kinda like paintball). I was in charge of the AI component for simulating the computer controlled opposing team. Since this genre was new to me (I don’t play these kinds of games, real life or otherwise), I had to do some research and thinking.

Visual and aural range AI component I came up with using a visual and aural component for the AI. The enemy would have the standard 60 (or 45 or 90) degree field of vision, and this has a cutoff distance (or a gradual decline of visibility). Then there’s 360 degree aural sensory input, but with a small cutoff distance.

This allowed seeing long distances but with a narrow scope. Rendering fog only limits the player. Computer controlled enemies can see till infinity, hence the cutoff distance. Well, if we limit the vision, then a player can sneak up to an enemy from behind and whack him on the virtual head. Not realistic.

So I thought up a 360 degree “alarm” system by incorporating an aural component. Any sound made by the player such as moving on sand (or water or gravel) and firing would alert the enemy (from behind, sideways, anywhere).

I was going to add in some sensitivity control to the aural component, like more receptive from in front than from behind. Then I decided that long distance communication, slow responses and school work was too much. So I sent a polite email to the team leader saying I’m glad to have been part of the team and I really need to focus on my studies. Then I left.

That ended my short-lived stint as a game developer.

This just came into my mind. In a virtual environment, autonomous agents can be omnipresent and omniscient. They can be anywhere in the blink of an eye and know everything. In a virtual environment, we try to limit the capabilities of our simulations to create a believable, realistic character.

In the real world, we try to expand the capabilities of our simulations running in robots. In our physical world, robots already face lots of limitations.

I see a squeeze theorem event waiting to happen…

6 month long projects are so last century

Hourglass with spider web Recently, I received a company-wide email complimenting a few groups of people for excellence. Those groups worked hard together for a project and successfully launched it. There was this particular one praising about 10 people for giving their best and sticking it out for 6 months.

That, is freakin’ long.

I can’t believe anyone going through a lengthy project like that in these recent times. A console game, I can understand, and it typically takes about 2 years for a game to be completed. It’s extremely hard to correct mistakes after a console game is launched, so there’s a lot of coding and testing to do. I mean, how can one apply a patch after a game is out?

Start-ups are even more taxing. I was working in one such start-up software company, and the implied timeline given was one year. At the end of that one year, some product had better be launched and profits coming in, or the start-up company’s going under. Rent, programmer salary and flagging confidence of the entrepreneur will slowly drain the resources of the company for anything longer than a year.

The world is getting flatter. Individuals now hold as much power as large companies. Open source projects are on par with proprietary software, and sometimes at a fraction of the cost (some even free). Software management and development needs to move faster.

6 month long projects are just so last century.

If not for the fact that my company is large enough, I doubt that project mentioned above would have done anything to the bottom line. It would have taken longer to reap the rewards of that project. And sometimes, that’s a luxury smaller companies and individuals cannot afford.

6 months. 10 people to be paid. And nothing to be gained in between? Those rewards had better be good…

[start of small digression]
My colleague recently gave birth to a healthy baby girl (congratulations!). Nature has designated that 9 months is sufficient for a human baby to be fully formed enough to be born.

Baby in blanket
A baby doesn’t have to be born extremely clever. A baby doesn’t have to be physically strong. A baby just needs to be as complete as possible at the point it’s born, and have the potential to grow.

And no, that’s not my colleague’s baby girl…
[end of small digression]

How can a baby grow further? Be out here in our world. How can individuals, small businesses and large companies grow further? By putting themselves out here in the world. How can software grow? By being tested in our world.

All the documentation, design, coding, testing, meetings and discussions and opinions mean naught if the software doesn’t work in the real world. And you only know if it really works when it’s out here, in our world.

Faster iterative cycles

That’s why agile methodology recommends smaller and faster iterative coding and testing. Code, launch, test, get feedback, code better, relaunch, test again, get more feedback, and so on. Of course, there comes a time when launching into the real world works better than launching into a test environment. Well, release the software product, and get back to making it better.

Launch your software with as complete a feature set as possible, and as soon as possible. My users are usually ecstatic over a small launch into production, be it just a new interface that really helps their job, or a small web application catering to a customer need.

Why? Because with faster launches, they can garner more businesses at a faster rate. Sometimes, customers don’t need a million dollar application with 100 plus features (most of which will never used). They just want a 3-screen interface application that does a really good job of retrieving data, because that’s all the customer really wants. Anything else is fluff, nice to have but hardly earth-shaking if absent.

And when the application is launched, there will be real-world feedback from the customer, real suggestions and improvements to be made instead of the hypothetical business cases when planning the original million dollar application.

How do you get faster launches with your projects? Break it down into the smallest, most complete application that satisfies the requirements, and launch that. Then move to the next phase by implementing the next most complete superset of the features you cut out from before, and launch that.

In the process of doing this, you may find you no longer need some features, because then, you’ll really and truly look at what provides the most value for the customers and users from the application.

My real life example

There was this one project I did. My whole team had rescheduled everything else, because the customer was a huge deal, and the time given was one month. My users worked hard to obtain that customer contract. Sales people selling, customer service people servicing and administrative people administrating. My team was tasked with the IT part, porting data, managing data, calculations and processing. Me? I was in charge of the web application, the very interface that customer has with all that data.

During that period, I was in the middle of helping two teams with development work. Two teams, two projects. Torn between two teams and faced with looming deadlines, multitasking was definitely out of the question. I had to focus all my energy into completing one project before the other, because it’s the fastest way to complete both within the time period.

For my main team’s project, I had to come up with a fresh design from scratch, all by myself, and I had to make sure that it’s scalable. Knowing my users, they’re going to add more features so their customer remains satisfied and they remain productive. For the other, I had to do code reviews, code improvements and some documentation.

A one month deadline. Somehow, I managed to come up with a usable, scalable web application. Somehow, I managed to complete the development work for two teams. All in one month.

You know what? After the launch of that web application, my users started asking for more features. I’m sad, because I had to go through intense deadline cycles again. I’m also glad, because it meant the customer was satisfied, and my users found the interface useful. No corrections, just improvements.

Wrapping it up

Shrinking project deadlines forces you to think about the software, from requirement to design to code. Deadlines measured in months are for consultants. Deadlines measured in weeks are for real programmers.

Discuss.

PageRank, BlogRush and SEO Title Tag

Ok, this is more like a news update. There’ve been a few events happening on the Internet, their effects rippling slowly until they hit me… all at about the same time.

So last Saturday, I decided to do something about them, which were basically minor updates to the blog.

1. Google PageRank

The blogosphere was rife with discussion on PageRank lately. Apparently, Google was making some changes to their algorithms and several sites and blogs were penalised with a PageRank hit.

The main reason cited for this mass update was the selling of text links. Google frowns on it, because Google has a hard time telling which links are valuable, and which aren’t.

You can still sell text links. You just need to add in the nofollow attribute, like so

<a rel="nofollow" href="yourlink.html">Your text</a>

I used to be a publisher in the Text-Link-Ads network. I joined primarily because I could append some ads into my blog feed, which was cool then. During the test period when I first stuck the php code into my blog, I didn’t like the look of the links. I couldn’t find a nice way to display them, and there’s very little I could do in their control panel.

Well, I didn’t get any advertisers anyway, and from what I remember, when the links do appear, they didn’t have the nofollow attribute. No advertisers, no control, so I took it out.

2. BlogRush Phase 2 rollout

I installed the BlogRush widget when it first came out, and sad to say, I haven’t had much traffic from it yet. Still it looks pretty cool, and I can find other bloggers with similar interests through it, so it’s still useful.

There were some massive blog accounts removed (some 10000 of them) due to the people attempting to cheat the system. I sat through the flurry of activity and experienced first hand how a new network go about fixing problems.

Anyway, one of the improvements in phase 2 (on October 31) was the expansion of categories and sub-categories. The new categories were only implemented on November 2, so I had to wait a bit. I originally placed this blog under “Computers & Internet”. It was the closest category I could find, and I got all sorts of weird posts appearing in my widget.

Thankfully, they came up with a sub-category “Programming & Web Development”. Whew…

There’s also an option to use a thinner widget because some members couldn’t fit the standard 175 pixel width into their blogs. The thinner widget is 120 pixels wide. I tried it on. Too narrow. Text too cramped. Reverted to 175 pixels.

Changing colours (or “flavors”) doesn’t require recopying JavaScript code. Changing sizes do. I checked out the differences in the JavaScript involved. Compare this partial fragment of the original


http://widget.blogrush.com/show.js

to this (the thinner version)


http://widget.blogrush.com/show_2.js

Subtle…

3. SEO Title Tag plugin

Recently, I updated this blog from WordPress version 2.2 to 2.3.1. As of now, the plugins I dropped out were Ultimate Tag Warrior, Subscribe to Comments and now the Text-Link-Ads. I installed the beta version of SEO Title Tag, and the final version was only just ready.

No major changes were required to upgrade to SEO Title Tag 2.1.0, though I had a problem with permissions for creating the table wp_seo_title_tag_tag… Being the proficient programmer that I am, I figured out the SQL statement for the database table creation from the .php plugin file. Then I went in and flexed my SQL muscles and voila, table created!

I decided figuring out why access permissions were denied in WordPress was too much of a bother on a Saturday afternoon…

Using and formatting DateTime and TimeSpan data types

One of the most useful constructs in the .NET Framework is the ease of use for date/time manipulation. I need to manipulate dates and time frequently, either displaying them or parsing strings containing them.

Let me show you the 5 easy ways to get a DateTime variable.

DateTime dt;
dt = DateTime.MinValue;
Console.WriteLine(dt.ToString());
dt = DateTime.MaxValue;
Console.WriteLine(dt.ToString());
dt = DateTime.Today;
Console.WriteLine(dt.ToString());
dt = DateTime.Now;
Console.WriteLine(dt.ToString());
dt = DateTime.UtcNow;
Console.WriteLine(dt.ToString());

The DateTime.MinValue represents year 0001, January 1st, on the 0th hour, the 0th minute and 0th second.

The DateTime.MaxValue represents year 9999, December 31st, on the 23rd hour, the 59th minute and 59th second.

The DateTime.Today represents today. Taking the date of this post, it’ll be year 2007, November 2nd (zeroes for the other values).

The DateTime.Now represents today with the time component. Taking the date of this post again, it’ll be year 2007, November 2nd. And (for example) the time is 9th hour, 1st minute and 34th second.

The DateTime.UtcNow represents today with the time component, in Universal Coordinated Time. Taking the date of this post again, it’ll be year 2007, November 2nd. And (for example) the time is 1st hour, 1st minute and 34th second. I’m in Singapore, so the time zone offset is 8 hours ahead of UTC.

DateTime.UtcNow is particularly useful when you deal with international data, where the dates and times can span across many countries. In this case, having one standard time offset makes manipulating and displaying dates and times easy. Then people won’t keep asking “Is this American time, or London time, or Singapore time?” Just display, and let the users add or subtract their own time zone offset to obtain data in their local time.

Specific date/time values

What if you need to create DateTime variables with a specific date and time?

DateTime dt;
// 2nd Nov 2007, 1:15 pm, 45th second, 853rd millisecond
dt = new DateTime(2007, 11, 2, 13, 15, 45, 853);
Console.WriteLine(dt.ToString());
// get the same date by parsing a string
dt = DateTime.ParseExact("20071102131545", "yyyyMMddHHmmss", null);
Console.WriteLine(dt.ToString());
// get the same date by parsing a string formatted differently
dt = DateTime.ParseExact("02/11/2007 13:15:45", "dd/MM/yyyy HH:mm:ss", null);
Console.WriteLine(dt.ToString());

I prefer using the ParseExact() function rather than Parse(). I like to have exact control over how a date/time string is interpreted, and I want any culture-specific information to be left out of the parsing. If you know exactly what you have and what you need, it’s better to do it yourself rather than letting the code do implicit conversions. I’m paranoid that way…

Displaying dates and times

Then there’s displaying them

DateTime dt;
dt = new DateTime(2007, 11, 2, 13, 15, 45, 853);
// get 2 Nov 2007 01:15 PM
Console.WriteLine(dt.ToString("d MMM yyyy hh:mm tt"));
// get November 02, 2007 13:15
Console.WriteLine(dt.ToString("MMMM dd, yyyy HH:mm"));
// get 2007-11-02T13:15:45.8+08:00
Console.WriteLine(dt.ToString("yyyy-MM-ddTHH:mm:ss.fzzz"));

The last one is in the format of the one submitted for discussion in W3 Consortium. Refer to the Microsoft documentation of date and time formats for more information.

Obtaining first and last days of the month

In my work, I’ve often had to deal with special dates, like the first and last days of the month. So how do you accomplish this?

DateTime dtStart, dtEnd;
int iDaysInMonth = 0;
dtStart = DateTime.Now;
dtStart = new DateTime(dtStart.Year, dtStart.Month, 1, 0, 0, 0, 0);
dtEnd = DateTime.Now;
iDaysInMonth = DateTime.DaysInMonth(dtEnd.Year, dtEnd.Month);
dtEnd = new DateTime(dtEnd.Year, dtEnd.Month, iDaysInMonth, 23, 59, 59, 999);
Console.WriteLine("The first day of the month is {0}", dtStart.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine("The last day of the month is {0}", dtEnd.ToString("dd/MM/yyyy HH:mm:ss"));

The trick to obtaining the last day of the month is the DateTime.DaysInMonth() function. The number of days in the specific month, is also the last day of the month. No fuss, no muss.

This is way better than you implementing a custom function, which probably involves some arcane calculation with leap and non-leap years. If you do it wrongly, you’ll end up with 28 days instead of 29 for certain February’s. The DateTime.DaysInMonth() function is impervious to these mistakes.

Duration calculation with TimeSpan

Next, we have calculations of duration. This is where TimeSpan comes in. An example illustrates its use better.

DateTime dtStart, dtEnd;
dtStart = new DateTime(2007, 10, 27);
dtEnd = new DateTime(2007, 11, 2, 13, 15, 45, 853);

TimeSpan ts = dtEnd - dtStart;
Console.WriteLine(ts.Days);
Console.WriteLine(ts.Hours);
Console.WriteLine(ts.Milliseconds);
Console.WriteLine(ts.Minutes);
Console.WriteLine(ts.Seconds);
Console.WriteLine(ts.Ticks);

Console.WriteLine(ts.TotalDays);
Console.WriteLine(ts.TotalHours);
Console.WriteLine(ts.TotalMilliseconds);
Console.WriteLine(ts.TotalMinutes);
Console.WriteLine(ts.TotalSeconds);

You’ll notice 2 different sets of properties. The Days property refers to the value of TimeSpan variable for the “day” part. The TotalDays property refers to the number of days in the duration. Similarly for the other “Total”-prepended properties. Just print out the values to get a feel of the differences.

Now for a more specific and practical example. How do we calculate the number of days between two dates?

DateTime dtStart, dtEnd;
TimeSpan ts;

dtStart = new DateTime(2007, 2, 26);
dtEnd = new DateTime(2007, 3, 2);
ts = dtEnd - dtStart;
Console.WriteLine(ts.TotalDays);

dtStart = new DateTime(2008, 2, 26);
dtEnd = new DateTime(2008, 3, 2);
ts = dtEnd - dtStart;
Console.WriteLine(ts.TotalDays);

The above gives 4 days (26 Feb, 27 Feb, 28 Feb and 1 Mar) and 5 days (as before, plus 29 Feb) respectively. Note that the leap years are also taken care of. The end date is not included in the calculation. Since the end date is at the very start of the day (0th hour, 0th minute, 0th second), it’s not counted, as far as duration is concerned.

But, what if you need the number of months instead? How do you do it? Well, you don’t need TimeSpan for this…

DateTime dtStart, dtEnd;
dtStart = new DateTime(2006, 11, 15);
dtEnd = new DateTime(2007, 2, 15);
int iNumberOfMonths = (dtEnd.Year * 12 + dtEnd.Month) - (dtStart.Year * 12 + dtStart.Month);
Console.WriteLine(iNumberOfMonths);

Just because it looks like something, doesn’t mean it has to be that something