Beginning C# – Formatting output

Real math formulae @iStockphoto / pinobarile Many times when we’re busy churning out code and worrying about the accuracy of our calculations, we can forget that ultimately our users are looking at the results. We have to care about how to present those precious calculations so our users can make sense of it.

And it’s appalling that there are programmers who make up algorithms and write custom functions to get those presentation formats, when the programming language often has a perfectly good in-built function for it. We have to become masters of our chosen programming language! We can start with the following code example.

int numberofapples = 7;
short numberoforanges = 16;
byte red, green, blue;
float distanceinmetres = 42769.307f;
decimal priceofcomputer = 2495.95m;

red = 107;
// the following two lines will fail compilation
// because the values are out of [0, 255] range
//green = -34;
//green = 256;
green = 214;
blue = 0x3f; // this is 63

// this pads the number with zeroes on the left until
// there are 5 digits. If the number is already 5 or
// more digits, then the number is simply printed out.
Console.WriteLine(numberofapples.ToString("d5"));
Console.WriteLine(numberoforanges.ToString("d5"));

// in this case, the number is converted into a string,
// then it's padded on the left with spaces (default) until
// there are 5 characters.
Console.WriteLine(numberofapples.ToString().PadLeft(5));
 // this time, we pad with the letter v (instead of spaces)
Console.WriteLine(numberoforanges.ToString().PadLeft(5, 'v'));

// the maximum number of placeholders is 3: {0}, {1} and {2}
// To go beyond 3, you'll have to use this syntax
//Console.WriteLine("{0}, {1}, {2}, {3}, {4}", new object[] { red, green, blue, 8, 13 });
Console.WriteLine("\\nRGB triplet is [{0}, {1}, {2}]", red, green, blue);
Console.WriteLine("In hexadecimal, they're [{0,0:x2}] [{1,0:x4}] [{2,3:x2}]\\n", red, green, blue);

Console.WriteLine("Distance is {0}", distanceinmetres.ToString("f2"));
distanceinmetres = 42769.304f;
Console.WriteLine("New distance is {0}", distanceinmetres.ToString("f2"));
Console.WriteLine("Distance in scientific notation is {0:e}", distanceinmetres);
Console.WriteLine("Scientific notation (2 dec places) is {0:e2}", distanceinmetres);

Console.WriteLine();

Console.WriteLine("Computer price:\\t{0:N}", priceofcomputer);
Console.WriteLine("Or this way:\\t{0:C}", priceofcomputer);
Console.WriteLine();

DateTime timenow = DateTime.Now;
Console.WriteLine(timenow.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine(timenow.ToString("yyyy-MM-ddTHH:mm:sszzz"));
Console.WriteLine(timenow.ToString("dddd, MM/dd/yyyy"));
Console.WriteLine(timenow.ToString("d MMM yyyy"));
 // for more formats, search MSDN for "Custom DateTime Format Strings"

Console.WriteLine("End of program");
Console.ReadLine();

There’s quite a bit of commenting, so you can follow better while reading the code. It saves a lot of explanation in the post too. There are only a few things I want to point out.

Hexadecimal values
Any integer variable type can be assigned a hexadecimal value instead of plain vanilla numbers. Perhaps the value to be assigned is the result of a binary OR. In this case, hexadecimal values give a clearer idea of how the result is obtained, such as 0xf0 | 0x33 becomes 0xf3.

Hexadecimal values are also used in colour representations, as illustrated in our example code.

Special characters
In the example code, two new characters are introduced: \n and \t. The former is a new line character, and the latter is a tab character. They are also known as escape characters. The backslash \ escapes the normal meaning of the following character. So the “n” is not really printed out.

Automatic rounding
When the float value 42769.307f is printed to 2 decimal places, it’s rounded up to 42769.31. When 42769.304f is printed to 2 decimal places, it’s truncated to 42769.30.

Despite the convenience, I strongly suggest you do not let the computer determine your result. If you want it rounded up, ensure the result yourself.

Thousands separator
Sometimes, when the user deals with numbers in the millions, it’s hard to determine the value of a number such as 43526176849. The user has to count the digit positions to know it’s about 43 billion. This is where using “N” in the format string helps. Commas are used to separate every thousandth digit. Commas are the commonly used separator. If you live in Germany, it’s a period “.”. If you live in Sweden, it’s a space.

The “C” format string is for currency.

Date/Time formats
The combinations for formatting dates and times are the most formidable ones I’ve ever encountered. I am inclined (and due to work requirement) to use the date format used in England, where the day is before the month, like so dd/MM/yyyy.

If you’re working in ASP.NET, I suggest you don’t rely on the culture of the globalisation tag in web.config. There are short cuts for date formatting, such as DateTime.Now.ToString("d") which gives the short date version. I personally find this lacking in descriptive detail. I prefer to manually set the format string. This way, I know what’s gonna come out.

Output
Formatting output screenshot

Homework
Go search MSDN for all the possible format strings, particular those for dates and times. Then play around with the source code. Have fun!

Download source code.

Beginning C# – Arrays and iterations

Numbered mailboxes @iStockphoto / Eliza Snow So you’ve learnt a bit about variables such as ints and floats. What happens if you need, say a bunch of integer variables with similar purposes? For example, ten decimal variables to store prices. This is where arrays come in.

One and two dimensional arraysArrays offer a simple syntax to declare a series of variables of the same type with minimum work. Think of arrays as boxes in sequential order, where the boxes can only hold a certain type of item.

When someone uses the term “array”, the person usually means a one-dimensional array. What’s the difference? Imagine you have a series of boxes. That’s a one-dimensional array. Then imagine each of those boxes is the start of another series of boxes. That’s a two-dimensional array. You can even go on to three-dimensional arrays, where you stack two-dimensional arrays on top of each other.

Alright then, how do you use them? Here comes the source code.

            const int numberofelements = 10;
            double[] multiplesofpi = new double[numberofelements];
            int i;

            for (i = 0; i < numberofelements; ++i)
            {
                // The result of an operation between two numbers has
                // the precision of the number with the higher precision.
                // Math.PI is a double, which has a higher precision than
                // i, an integer. So the result of i * Math.PI is a
                // double.
                multiplesofpi[i] = i * Math.PI;
            }

            // reverse the for loop
            for (i = numberofelements - 1; i >= 0; ----i)
            {
                Console.WriteLine("Box {0} has {1}", i, multiplesofpi[i]);
            }

            Console.WriteLine("End of program");
            Console.ReadLine();

So we declare an array of doubles named multiplesofpi. Note the square brackets after the double. This line

            double[] multiplesofpi = new double[numberofelements];

just tells the compiler that we want an array of doubles. The new keyword simply tells the compiler to create a new array of doubles, with “numberofelements” number of doubles bunched together. Remember the const keyword we learnt?

            for (i = 0; i < numberofelements; ++i)
            {
                // The result of an operation between two numbers has
                // the precision of the number with the higher precision.
                // Math.PI is a double, which has a higher precision than
                // i, an integer. So the result of i * Math.PI is a
                // double.
                multiplesofpi[i] = i * Math.PI;
            }

In the for loop, we assign each element of the array with a value. Each array element can be accessed using an index, which in our case is the variable i.

There are 10 iterations in this case. An iteration refers to an instance of something being done repetitively, such as in a for loop, or while loop. In each iteration, we multiply the number of the iteration by the value of PI, which is about 3.14159. The Math library provided by .NET already contains the constant value of PI, so we’ll just use that.

It takes some getting used to, but computers really like counting from zero. We humans start counting from 1, and for a long time, cannot grasp the idea of nothingness. Computers however, have no problems with zero. Maybe they’re more advanced than us humans…

Anyway, we then practise reversing the for loop with

            // reverse the for loop
            for (i = numberofelements - 1; i >= 0; ----i)
            {
                Console.WriteLine("Box {0} has {1}", i, multiplesofpi[i]);
            }

This is important, because there will come a time in your programming life where going backwards and forwards in a sequential manner is critical. Besides, it trains your mind to think differently, and that’s great by itself.

Homework
Write the first for loop in reverse manner. Then try writing the second for loop in forward manner. Convince yourself that the array will contain the same values, regardless of whether the for loop is in forward manner or reverse manner.

Download the source code.

Beginning C# – Loops and increments

Part of a computer’s charm is its ability to do repetitive tasks in a consistent manner. Doing lightning fast calculations? Good. Doing those calculations with accurate results? Better. Doing those calculations with accurate results everyday for the past year and not complaining? Oh my goodness!

The basis of programming this repetitive behaviour is the loop. There are 4 kinds of loops:

  • for loop
  • while loop
  • do-while loop
  • foreach loop

We’ll look at the for and while loops since they’re more common. In the following example code, we’ll be looking at the calculation of factorials. The factorial of 5, represented in mathematics as 5!, is equal to 1x2x3x4x5 = 120. From Wikipedia’s description of factorials,

In mathematics, the factorial of a non-negative integer n is the product of all positive integers less than or equal to n

Oh yes, the example code:

            const int cnFactorial = 7;
            // the following line of code will fail
            // because cnFactorial is a constant
            //cnFactorial = 5;

            int i, result;

            result = 1;
            for (i = 1; i <= cnFactorial; ++i)
            {
                result = result * i;
            }
            Console.WriteLine("Factorial for {0} is {1}", cnFactorial, result);

            result = 1;
            i = 1;
            while (i < cnFactorial + 1)
            {
                result = result * i;
                i++;
            }
            Console.WriteLine("Result is {1} for {0}!", cnFactorial, result);

            Console.WriteLine("End of program");
            Console.ReadLine();

Constants
Right there on the first line, we hit our new keyword const. It makes our integer variable cnFactorial a constant. Any value first assigned to cnFactorial can never be changed thereafter. Certain values are always the same, like PI (3.14159) or the number of months in a year (12). Adding the const keyword in front of a variable declaration fixes that value, reducing programming errors in case we super coders forget and happen to change an unchangeable value.

The resulting executable is also leaner because the computer compiler will, in effect, replace every occurrence of the constant variable’s name with the constant value. This means that program only has the constant value, and not the constant variable! Constant values take up less space in a program than variables.

Anatomy of a for loop
The for loop has 3 parts, separated by semicolons: initialiser, terminator and incrementor.
for (initialiser; terminator; incrementor)

The initialiser sets the starting conditions for the for loop. This is a good place to code any variable assignments such as resetting variable values.

The terminator is where you code the stopping condition for the for loop. Many a programmer has failed at least once, where they gave the wrong stopping condition and the for loop never ends. At best, the infinite loop keeps printing out messages. At worst, the computer crashes. Code with caution!

The incrementor is where something is usually changed, before checking the terminating condition.

It’s easier to just go through the code:

            result = 1;
            for (i = 1; i <= cnFactorial; ++i)
            {
                result = result * i;
            }

First, we assign the value of 1 to the variable “result”. Then in the initialiser of the for loop, we assign 1 to the variable i. There’s this unofficial type of variable which I’ll call the “loopers”. These looper variables are declared for the sole purpose of running through the for loop. They are also usually single characters by name. i, j, k and a, b, c and p, q, r and x, y, z are the more common ones.

Then the terminating condition reads “If i is less than or equal to cnFactorial, continue”.

The code in the incrementor, ++i, is a shortcut for “Add 1 to the value of i, then assign this new value to i”. It is equivalent to

i = i + 1;

Then the contents of the for loop reads “Multiply the value in variable ‘result’ by the value in variable ‘i’, and then assign this new value to ‘result’.”

The whole flow of the logic is like this:

  1. result has value of 1
  2. Start of for loop, i has value of 1
  3. Check that i (1) is less than or equal to cnFactorial (7), which is true so…
  4. Assign result (1) * i (1) which is 1 (1*1) to result
  5. Do ++i, so i now has value of 2
  6. Check that i (2) is less than or equal to cnFactorial (7), which is true so…
  7. Assign result (1) * i (2) which is 2 (1*2) to result
  8. Do ++i, so i now has value of 3
  9. Check that i (3) is less than or equal to cnFactorial (7), which is true so…
  10. Assign result (2) * i (3) which is 6 (2*3) to result
  11. Do ++i, so i now has value of 4
  12. Check that i (4) is less than or equal to cnFactorial (7), which is true so…
  13. Assign result (6) * i (4) which is 24 (6*4) to result
  14. Do ++i, so i now has value of 5
  15. Check that i (5) is less than or equal to cnFactorial (7), which is true so…
  16. Assign result (24) * i (5) which is 120 (24*5) to result
  17. Do ++i, so i now has value of 6
  18. Check that i (6) is less than or equal to cnFactorial (7), which is true so…
  19. Assign result (120) * i (6) which is 720 (120*6) to result
  20. Do ++i, so i now has value of 7
  21. Check that i (7) is less than or equal to cnFactorial (7), which is true so…
  22. Assign result (720) * i (7) which is 5040 (720*7) to result
  23. Do ++i, so i now has value of 8
  24. Check that i (8) is less than or equal to cnFactorial (7), which is false so we terminate the loop! Whoopee!

The purpose of that incredibly and mind-numbingly long and tedious explanation is so you can appreciate how obliging the computer is when performing repetitive tasks. Anyway, we then print the result. This time, we format the output a little.

            Console.WriteLine("Factorial for {0} is {1}", cnFactorial, result);

The {0} and {1} are placeholders, where {0} refers to the first value (cnFactorial) and {1} refers to the second value (result) after the string.

Why does {0} refer to the first value? Good question. Unfortunately I don’t have an easy answer. It is primarily due to the ancient programming custom of offsets, where the first item is offset by 0 positions. The second item is offset by 1 position. This has caused many beginner programmers to falter.

Homework
Unravel the logic for the while loop in the manner demonstrated above. Yes it’s tedious, but it’ll make you a better person. The while loop takes in only the terminating condition.

You’ll also notice the i++ and it does exactly the same thing as ++i. What’s the difference? Ahhh… but that is your second piece of homework. *grin*

Download source code.

Beginning C# – Precision and control

So you’ve learnt about variables, and you’re wondering, “What’s the practical difference between float, double and decimal variable types?” The difference is in precision.

floats represent single precision real numbers, known as such because of the floating point (or decimal point). doubles represent double precision real numbers, taking up two times the storage space of a float (different from representing two times the range of a float). decimals are a bit special, as they can represent up to 28 significant figures. It’s easier to just show you, so here’s the example code (only contents of the Main function).

            float lowprecision;
            double highprecision;
            decimal exactprecision;
            lowprecision = 1.61803398874989484820f;
            highprecision = 1.61803398874989484820;
            exactprecision = 1.61803398874989484820m;

            Console.WriteLine(lowprecision);
            Console.WriteLine(highprecision);
            Console.WriteLine(exactprecision);

            if (5 > 3)
            {
                Console.WriteLine("First condition");
            }
            else
            {
                Console.WriteLine("Second condition");
            }

            // variables can be declared and assigned a value
            // on the same line of code.
            int truthchecker = 17;
            if (truthchecker == 17)
            {
                Console.WriteLine("The truth is the number 17.");
            }

            if (truthchecker != 17)
            {
                Console.WriteLine("The truth is NOT the number 17.");
            }

            /* The following if-else statement is equivalent to the above
             * two if statements.
             * This comment also illustrates how to use a multiline comment.
             * */
            if (truthchecker == 17)
            {
                Console.WriteLine("2nd check: The truth is the number 17.");
            }
            else
            {
                Console.WriteLine("2nd check: The truth is NOT the number 17.");
            }

            Console.WriteLine("End of program");
            Console.ReadLine();

I’ve used a prominent mathematical number, the golden ratio, as an assigned value for our float, double and decimal variables. You should have noticed the “f” at the end of golden ratio for the float variable assignment, and the “m” for the decimal variable. These are known as suffixes, and there are other suffixes for other variable types. For now, just remember to append an “f” for floats, and an “m” for decimals.

Output for float, double and decimal
When you print the variables, you get 1.618034, 1.61803398874989 and 1.61803398874989484820 respectively. The difference is due to the size of the variable type, affecting how a variable stores a value. So even though the assigned value is the same, the storage and thus the stored value is different for the three variables.

One practical use of preferring floats over the other two types is their speed. Smaller storage sizes translates to faster calculation speeds, while sacrificing accuracy. This is particularly useful in games, such as calculating 3D positional points where the results don’t have to be accurate as much as being quickly computed. The player isn’t going to notice that a box is 0.000005 units off to the left, because he’s too busy shooting some dastardly evil aliens.

When accuracy is extremely important, such as in financial applications, decimals come into play. There are real numbers that floats and doubles cannot represent exactly. For example, the only money values a float or double can represent exactly are 0.00, 0.25, 0.50 and 0.75 (or any dollar amount with those cent values, like 14.75). Why is this? Short answer is it’ll take too long to explain. Try searching with the words “exponent” and “mantissa”. Anyway, with 28 significant figures for accuracy, decimals are ideal for financial applications.

Decisions, choices and forks
Next we learn a new concept: the if statement, one of the most powerful and most used construct for controlling program logic flow.

            if (5 > 3)
            {
                Console.WriteLine("First condition");
            }
            else
            {
                Console.WriteLine("Second condition");
            }

Note where the round brackets () and the curly brackets {} are used.
The above code can be read as “If 5 is greater than 3, then print ‘First condition’, otherwise, print ‘Second condition'”.

The if statement can also be used alone without the else part, such as

            if (truthchecker == 17)
            {
                Console.WriteLine("The truth is the number 17.");
            }

Note: The double equals mean mathematical equality. A single equal mean assignment.
In English, the above code reads “If the variable ‘truthchecker’ is equal to the number 17, print ‘The truth is the number 17.'” Some programmers prefer to reverse the check, like “17 == truthchecker“, to avoid confusing equality checks and assignments. I find it kinda funny to check in reverse, so take your pick.

Then there’s the converse.

            if (truthchecker != 17)
            {
                Console.WriteLine("The truth is NOT the number 17.");
            }

The exclamation mark followed immediately by an equal sign means “not equal to”. So the chunk of code reads “If the variable ‘truthchecker’ is not equal to the number 17, print ‘The truth is NOT the number 17.'”

Multiline commenting
Two consecutive forward slashes // means whatever follows on the same line is a comment, and to be ignored by the computer. What if your comments are too long and go over the next line? You can start another line with // and continue writing comments. Or if you can start your comments with a forward slash and an asterisk /* and end your comments with an asterisk and a forward slash */, which achieves the same effect.

Homework
Wow, that was a long lesson. So homework will be short. Download the source code, and replace the line

if (5 > 3)

with

if ((5 * 4) < (27 - 6))

Change the numbers around and see what happens.

Beginning C# – Variables and operations

So you’re sick with Hello World program code, and want to start doing something. Before you go writing your NASA-approved quantum space engine or the next blockbuster financial application, you have to know about how programs store and manipulate data.

Program data (such as rocket speed or stock prices) are stored in variables, which can be thought of as boxes holding information. We remember information differently from a computer. For example, the information “15” can be a number to us. Or part of an address such as “street 15”. Or 15 dollars. We can pretty much move this data around in our heads.

Here’s the thing: computers need structure. They must know that 15 is a number, and will only store 15 as a number. If 15 is to be part of an address, it must be stored as an address. Moving data from one form to another usually requires telling the computer explicitly to do so, which means you have to write specific code to do that. It’s easier to talk to a computer in its own terms, so we’ll learn about …

Variable types
There are a few variable types, and the most commonly used are those storing numbers and text. There are 2 kinds of number variables; whole numbers and numbers with decimal points (also known as real numbers). In C#, the whole number variables are byte, short and int. The other kind has float, double and decimal. There are more, but these are the common ones.

Why is there a difference? Because computers think, store and manipulate them differently. To the computer, a 7 and a 7.00 are two very different pieces of information. This is very important, especially if you’re doing mathematical calculations.

So we’ll go through them a little bit

  • byte – a whole number between 0 and 255 inclusive
  • short – a whole number between -32768 and 32767 inclusive
  • int – a whole number between -2147483648 and 2147483647 inclusive
  • float – a real number approximately between ±10-45 and ±1038
  • double – a real number approximately between ±10-323 and ±10308
  • decimal – a real number approximately between ±10-28 and ±1028

Why are the real numbers approximations? Again it’s due to the way computers store data. float and double variable types implement the IEEE standard. For now, we’ll simply learn more about these variable types through practical use. Which brings us to the sample code.

using System;
using System.Collections.Generic;
using System.Text;

namespace VariablesAndOperations
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            double anothernumber, yetanothernumber;

            number = 5;
            anothernumber = 3.14159;
            yetanothernumber = 2 * anothernumber;
            
            Console.WriteLine(number);
            Console.WriteLine(anothernumber);
            Console.WriteLine(yetanothernumber);

            number = 3 + 8;
            Console.WriteLine(number);

            // This indicates the end of the program

            Console.WriteLine("End of program");
            Console.ReadLine();
        }
    }
}

A closer look
The first two lines inside the Main function is

int number;
double anothernumber, yetanothernumber;

This is how we declare our variables. In this case, we tell the computer we want a variable of type int and we name it “number”. We also declare two variables of type double, named (unimaginatively) “anothernumber” and “yetanothernumber”. Variables of the same type can be declared on the same line by separating them with a comma.

The next three lines are

number = 5;
anothernumber = 3.14159;
yetanothernumber = 2 * anothernumber;

This is where we assign values to our variables. So we want the integer 5 to be stored in “number”. Then we want 3.14159 to be stored in “anothernumber”. The next line is more interesting. We want two times the value stored in “anothernumber” to be stored in “yetanothernumber”. This means we can assign any appropriate value to a variable, even if the value is stored in another variable.

Manipulating data basically involves mathematical operations (although they are others). They are addition, subtraction, multiplication and division. Their respective operations in code are +, -, * and /.

Commenting
Skipping a couple lines down, we encounter the double forward slash //. This simply tells the computer that whatever follows after the // on the same line is to be ignored, because it’s meant to be read by a human.

Additional note
If you’ve tried running the previous Hello World program straight from the directory by double clicking, you’ll find that it comes up and then disappears. Which is what the following lines will prevent:

Console.WriteLine("End of program");
Console.ReadLine();

By printing “End of program”, you’ll know that the program has indeed reached the end. The Console.ReadLine(); tells the computer to wait for input till the Enter/Return key is hit. This automatically solves the disappearing problem.

Here’s the source code for you to play with.

Homework
Try assigning

number = 1 / 4;
anothernumber = 1.0 / 4.0;

and print out the answer! Can you figure out why the values aren’t what you think they should be?

Beginning C# – Boring Hello World

Programming is about making the computer do what you want. Many programming languages exist, and I’ll concentrate on showing how you can learn C#, one of the easier languages in my opinion.

First, go to the Microsoft Visual Studio C# Express site, and download the free software compiler. A compiler is simply a software that turns your code to a program. The download link should look like this:
Visual Studio C# 2005 Express download

So you install the software and create your first C# project, and name it “ConsoleHelloWorld”. All you need is to add this line of code

Console.WriteLine("Hello World!");

and you’ll have the famous “Hello World” program!

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Compile and run the program in Visual Studio by using Ctrl + F5, or using the menu options [Debug] -> [Start Without Debugging].

The Hello World program is the simplest piece of code with a complete program structure. It is also one of the most boring pieces of code in existence because it does practically next to nothing. That said, the program structure is complete, so we’ll dissect that.

The using statements
These can be thought of as shortcuts for writing code. The following two lines of code are basically the same, thanks to the using System; statement.

Console.WriteLine("Hello World!");
System.Console.WriteLine("Hello World!");

The namespace keyword
It’s just a fence, making sure the code stays in a specific scope. And the meaning of “in scope” is … too much for you to handle at this point.

The class keyword
The “class Program” line of code just means that “Program” is a class, where “Program” is the name of your, uh, class. A class is a chunk of code containing instructions. … And is also too much for you to handle at this point.

The Main thing is …
Where all the action is taking place. It can take other forms besides

static void Main(string[] args)

but I’ll have to explain its other incarnations some other time.

So what can I tell you? Part of your programming experience is to simply ignore what you don’t know and write what code you do know. In our example, you just need to add one line of code. That’s it. Which reminds me. I haven’t explained what that line of code did.

Console is a class, and it has a function called “WriteLine”. If you feed the string “Hello World!” to the function WriteLine, it will be displayed. It’s called a “string” because it’s just a string or a series of characters.

I feel like I’m treating you like a fool, so instead of insulting your intelligence further, I suggest you pick up any C# beginner programmer book. I can almost guarantee the first chapter is on how to write a Hello World program.

And if you don’t get anything yet, then remember that part of being a fantastic programmer is the skill of selective ignorance.

Download source code

Programmer’s dilemma – Making tough choices

I’m lucky to be given relatively free reign in my design and coding decisions. Unfortunately, that often means I have to choose between what is right, and what is easy. Here’s a few of them:

Usability – If it’s optional, then don’t make it mandatory
When given the choice of optional fields, a user can and will take the path of least resistance, which is to leave all optional fields as is. I recently developed a web page that retrieves records from a database. All fields are optional. Consequently, everything from the database is retrieved. Which crashed my web server.

Since I was giving a presentation to a customer when this happened, I was just a tad embarrassed. After the presentation, I went back, made a few fields mandatory, with corresponding error messages to avoid Raymond’s feedback form experience. Sometimes, I have to be a user too.

Result oriented – Programmers Don’t Like to Code
I used to tell people I love programming. I’m not so sure now. Then I realised what I really love is solving problems, and that I can express my solution in a program. Even though solving that CSS display bug or optimising that loop gives me joy, it means little to the result-oriented user. So I have to choose practicality sometimes.

CSS Design – Suckerfish Dropdowns
There is this web application I’m maintaining that displays a menu for navigation. The code is unwieldy and makes use of some Javascript copied and pasted without much thought. Hideous to look at and horrendously tedious if I have add a new page. Luckily I found a more elegant dropdown menu solution. It means I have to redesign the navigation element, but it’s worth the effort.

The one you never want to meet – The Brillant [sic] Paula Bean
I have seen my fair share of obnoxious idiots of programmers, and chose patience and understanding instead of exclaiming their ineptitude. But Paula, the experienced Java programmer, raises stupidity to an art. Brillant!

Socialise or be ostracised – In Programming, One Is The Loneliest Number
Not only is programming by yourself lonely, but it’s dangerous to your code, health and social life. It was tough when I first started interacting with people I don’t know but were on my office floor. Don’t have any programmer colleagues? Get help by persuading your manager to hire another competent programmer.