Archive for the ‘Inspirational code’ Category.

Just being thorough

I always get a little nauseous when looking through someone else’s code and seeing things like this:

res = sqlite3_exec(database, [select UTF8String], NULL, NULL, &errorMsg);
if (res != outcome) {
    [testStringCapture appendFormat:@"%@,",obj]; //changed 2/2/2011
else {
    [testStringCapture appendFormat:@"%@,",obj]; //changed 2/2/2011

Alas, a little later on in the same method was some code that soothed my sensibilities as it is kind a perfect fit into the whole “do something here” theme:

res1 = sqlite3_exec(database, [select1 UTF8String], NULL, NULL, &errorMsg1);
if (res1 != outcome1) {
else {

As per usual, these code snippets are unedited (except for some formatting) portions of production code.

OK, you may have had a tough coach at some point growing up, but you have to let it go…

A co-worker found this nice little nugget in one of our sports web site applications:

Dim isAssHeadCoach As Boolean = Session("IsAssHeadCoach")

I hope it is meant to check for an assistant or associate head coach.

Is this string numeric?

This VB code was brought to my attention.  It is meant to look at a string variable (prefixText) and decide if the string is numeric or not, and return a data set (ds) by using a different method based on the result of the numeric test. (As always, this code is in a heavily used production environment.)

If Left(prefixText, 1) = "0" Or Left(prefixText, 1) = "1" Or Left(prefixText, 1) = "2" Or Left(prefixText, 1) = "3" Or Left(prefixText, 1) = "4" Or Left(prefixText, 1) = "5" Or Left(prefixText, 1) = "6" Or Left(prefixText, 1) = "8" Or Left(prefixText, 1) = "9" Then
    ds = New Users(_ConnStr).getUsersListByNumber(prefixText)
    ds = New Users(_ConnStr).getUsersListByLastName(prefixText)
End If

I have some great ideas on how to improve this code. The first thing I would have done was to use OrElse instead of Or, it would speed things up tremendously. And I would also have added in the test for the “7” character.

Highly useful Objective-C code

I just got the inspiration to add the following line of code to the app delegate header of my latest iPhone application:

#define  VERY_YES  YES

If you are wondering about the etymology of this, please check out the following informational message:

Where does the term “very yes” originate from?

I leave it to the imagination and creativity of my fellow developers to adapt this code to run in other flavors of C.  Please make sure to credit me if you decide to use it.

Best way to not use an enumeration, ever!

So here is some more interesting stuff found in some code that needed some emergency modifications.

The enumeration of this code starts on line 26 of the class file:

public enum City
    CLINTON = 78,
    FRANKLIN = 1,
    FAIRVIEW = 59,
    GREENVILLE = 55,
    SALEM = 83,
    MADISON = 81,
    ARLINGTON = 84,
    CLAYTON = 63,
    GEORGETOWN = 85,
    MARION = 15,
    OXFORD = 65,

And instead of using the MADISON enumeration, the if statement of this code starts on line 118 of the very same class file:

if (cityID == 0x51)
    actual = expected - actual;

The names were changed to protect the innocent, thanks to Wikipedia for having an easy to find list of common place names.

Because you never know how many days could be between Monday and Friday

Why do a couple of subtractions when two loops can do the same work?

while (processDate.DayOfWeek != DayOfWeek.Monday)
    processDate = processDate.AddDays(-1);
string mondayDate = processDate.ToShortDateString();
while (processDate.DayOfWeek != DayOfWeek.Friday)
    processDate = processDate.AddDays(1);
string fridayDate = processDate.ToShortDateString();

The illusion…

I have heard it said that the greatest danger is the illusion that all is well. This is sort of pessimistic, and I am not a pessimistic person by nature.

And then I start looking through the code and see something like this:

public Guid AddSomething(Guid id1, Guid id2, bool useAlternateValue)
    // stuff removed from here
    // including the creation of the obj object, 
    // which conains a default and alternate value
    string s = "";
    if (useAlternateValue && (obj.alternateValue != null))
        s = obj.alternateValue;
    else if ((!useAlternateValue) && (obj.defaultValue != null))
        s = obj.defaultValue;
    // more stuff removed from here

One of the developers that I work with is confused by my hatred of compounding the not operator with ands, ors, and parentheses in decision statements, and of the use of the null object. This code appears to combine both of these things in a mishmash of non functional code.

Brute force solution to a birthday riddle

At one point a long time ago, one of my college professors asked our class how many people it would take to put in a room before the probability that two of the people had the same birthday was greater than or equal to 50 percent, took guesses from a few of us students, and then told us the answer was 12. Coming from a professor, this had to be true.

That answer has not sat well with me lo these many years since my drinking days, so sitting here with nothing else to do, I decided to try a little Monte Carlo problem solving.

Here is my VS 2008 C# console application code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Birthdays
    class Program
        static int numberOfRuns;
        static int[] numberOfPeople;
        static List<int> birthdays;
        static Random rand;
        static int GetABirthday()
            int b;
            int maxDays = (rand.Next(1, 5) == 1) ? 367 : 366;
            b = rand.Next(1, maxDays);
            return b;
        static void Main(string[] args)
            rand = new Random();
            Console.WriteLine("Birthdays application");
            Console.Write("How many times would you like to run a birthday search? ");
            string s = Console.ReadLine();
            numberOfRuns = Convert.ToInt32(s);
            numberOfPeople = new int[367];
            for (int i = 0; i < 367; i++)
                numberOfPeople[i] = 0;
            Boolean leaveLoop;
            int b;
            int leapDayMatches = 0;
            int leapDayBirthdays = 0;
            int totalBirthdays = 0;
            for (int i = 1; i <= numberOfRuns; i++)
                birthdays = new List<int>();
                leaveLoop = false;
                while (!leaveLoop)
                    b = GetABirthday();
                    if (b == 366)
                    if (birthdays.Contains(b))
                        numberOfPeople[birthdays.Count() + 1]++;
                        leaveLoop = true;
                        if (b == 366)
            Console.WriteLine("Breakdown of number of people required:");
            int ctr = 0;
            for (int i = 2; i <= 366; i++)
                if (numberOfPeople[i] != 0)
                    ctr += numberOfPeople[i];
                    Console.WriteLine(string.Format("{0} people: {1} ({2:P})", i, 
                                        numberOfPeople[i], ctr * 1.0 / numberOfRuns));
            Console.WriteLine(string.Format("Total birthdays generated: {0}", 
            Console.WriteLine(string.Format("Leap day birthdays: {0}", 
            Console.WriteLine(string.Format("Leap day matches: {0}", 
            Console.WriteLine("Strike any key to end the program");

The answer yielded by the above code is 23, as any meaningful sample size plugged into the program above will demonstrate.

Of course, we did not have the internet back then, but now a quick Google search yields plenty of discussion of the theory and math behind the puzzle. If you are interested, click this link.

Friends don’t let friends reinvent System.Security.Cryptography

A fellow coworker is upgrading one of our long time customer’s ASP.NET web site that was originally created in 2003, and all is going swimmingly. Alas, this project could not go gently into that good night.

He makes the web page and code changes, modifies the database, pushes all the changes up to the web site, and the site is working well. Customers are placing orders on the web site, order e-mails are being sent to the site owners with encrypted credit card information, and all are happy.

But there is always a fly in the ointment. All of a sudden, an order is placed on the web site, but when the site owner tries to run a decrypt on the credit card information in the e-mail, the decryption routine is reporting a failure. So naturally, we assume that we broke the code somehow, so we started to dive into the project to see what we did to destabilize it.

He asked for my opinions on this problem, so I came over and we started to go through the VB.NET Framework v2.0 project. While investigating the area of the code containing the exact message that the customer was getting, my blood pressure started to go up right away as we started to see code that looked like this:

If intNumberLength = 16 Then
    'go through each of the 16 numbers and
    'add the code for them into the return string
    intNumber(0) = CType(Mid(strNumber, 1, 1), Integer)
    intNumber(1) = CType(Mid(strNumber, 2, 1), Integer)
    intNumber(2) = CType(Mid(strNumber, 3, 1), Integer)
    intNumber(3) = CType(Mid(strNumber, 4, 1), Integer)
    intNumber(4) = CType(Mid(strNumber, 5, 1), Integer)
    intNumber(5) = CType(Mid(strNumber, 6, 1), Integer)
    intNumber(6) = CType(Mid(strNumber, 7, 1), Integer)
    intNumber(7) = CType(Mid(strNumber, 8, 1), Integer)
    intNumber(8) = CType(Mid(strNumber, 9, 1), Integer)
    intNumber(9) = CType(Mid(strNumber, 10, 1), Integer)
    intNumber(10) = CType(Mid(strNumber, 11, 1), Integer)
    intNumber(11) = CType(Mid(strNumber, 12, 1), Integer)
    intNumber(12) = CType(Mid(strNumber, 13, 1), Integer)
    intNumber(13) = CType(Mid(strNumber, 14, 1), Integer)
    intNumber(14) = CType(Mid(strNumber, 15, 1), Integer)
    intNumber(15) = CType(Mid(strNumber, 16, 1), Integer)
    strCharCodes(0) = encrypt_Char1(intNumber(0), intIndexCode)
    strCharCodes(1) = encrypt_Char2(intNumber(1), intIndexCode)
    strCharCodes(2) = encrypt_Char3(intNumber(2), intIndexCode)
    strCharCodes(3) = encrypt_Char4(intNumber(3), intIndexCode)
    strCharCodes(4) = encrypt_Char5(intNumber(4), intIndexCode)
    strCharCodes(5) = encrypt_Char6(intNumber(5), intIndexCode)
    strCharCodes(6) = encrypt_Char7(intNumber(6), intIndexCode)
    strCharCodes(7) = encrypt_Char8(intNumber(7), intIndexCode)
    strCharCodes(8) = encrypt_Char9(intNumber(8), intIndexCode)
    strCharCodes(9) = encrypt_Char10(intNumber(9), intIndexCode)
    strCharCodes(10) = encrypt_Char11(intNumber(10), intIndexCode)
    strCharCodes(11) = encrypt_Char12(intNumber(11), intIndexCode)
    strCharCodes(12) = encrypt_Char13(intNumber(12), intIndexCode)
    strCharCodes(13) = encrypt_Char14(intNumber(13), intIndexCode)
    strCharCodes(14) = encrypt_Char15(intNumber(14), intIndexCode)
    strCharCodes(15) = encrypt_Char16(intNumber(15), intIndexCode)
    'strReturnValue = strCharCodes.ToString
ElseIf intNumberLength = 15 Then
    ' you get the idea

And this…

'first char
Select Case Left(strEncodeCard, 1)
    Case "X"    ' these character constants were originally all different
        strCardNumber(0) = "0"
    Case "X"    ' I have masked them out for this blog posting
        strCardNumber(0) = "1"
    Case "X"
        strCardNumber(0) = "2"
    Case "X"
        strCardNumber(0) = "3"
    Case "X"
        strCardNumber(0) = "4"
    Case "X"
        strCardNumber(0) = "5"
    Case "X"
        strCardNumber(0) = "6"
    Case "X"
        strCardNumber(0) = "7"
    Case "X"
        strCardNumber(0) = "8"
    Case "X"
        strCardNumber(0) = "9"
    Case Else
        blnSuccess = False
End Select

(The above code was repeated 32 times, once for each digit of a potential 16 digit credit card number, and there were two sets of these that were switched if the digit position was odd or even. There was definitely some thought put into this. I’m not saying it was good thought, just thought. Perhaps they were paid by the lines of code written?)

OK, I have done things like this from time to time, usually not to this extent, but the original designers and coders of this project at least had the good sense to encrypt the credit card information that was being e-mailed, so maybe it will get better.

Yeah, I was wrong about that, I should remember a tenet of code maintenance that I learned a long time ago: TWGW. (This stands for Things Will Get Worse.) As we stepped through the order that was confusing the system, we came upon this nugget.

'second, select the expiration year code
Select Case intExpYear
    Case 2003
        cryptoExp_Year = "X"    ' these character constants were originally all different
    Case 2004
        cryptoExp_Year = "X"    ' I have masked them out for this blog posting
    Case 2005
        cryptoExp_Year = "X"
    Case 2006
        cryptoExp_Year = "X"
    Case 2007
        cryptoExp_Year = "X"
    Case 2008
        cryptoExp_Year = "X"
    Case 2009
        cryptoExp_Year = "X"
    Case 2010
        cryptoExp_Year = "X"
    Case 2011
        cryptoExp_Year = "X"
    Case 2012
        cryptoExp_Year = "X"
End Select

Of course, the customer had a credit card that expired in 2013, and as such, no character was begin inserted into the encrypted string for the expiration year, and that was causing the problem.

I don’t even know where to begin, except to say that eventually this code was going to break, and that was the day. (System.Security.Cryptography was in .NET Framework v1.1, so they can’t use that as an excuse.) So the moral of the story is, if you are going to reinvent a Microsoft namespace, at least make it work more than six years.

A whole year of more randomer-ness

Today is the 1 year anniversary of a snippet of our company’s code being featured on The Daily WTF web site.  Here is a direct link to the article so you too can bask in the goodness of real randomicity:

More Randomer

So I bought cupcakes for our dev team and decided to hack one of the cupcakes:

More Randomer's First Birthday

By the way, the developer that created the code in question is no longer at the company.