CodeSOD: Pluralized!

"When digging through some code that was on the refactor list, I came accross some validation logic that checks if the user selected enough options on the form," writes Chris Osgood, "if enough options weren't selected, you'd get an error message along that said something like 'at least 3 options are required'."

"It took a little bit of coding to get that validate message. The '3' was obviously dynamic, and if there was only one missing selection, then 'are' was replaced with 'is'. As for the word 'option'...it was is PLURALIZED!"

/// <summary>
/// Changes a singular string to plural e.g. "Monkey" => "Monkeys".
/// </summary>
/// <param name="text">The text to PLURALIZE!</param>
/// <returns>A plural string.</returns>
public static string Pluralize(string text)
{
    if (text.Length == 0)
    {
        return text;
    }

    string result = text;

    if (result.Equals("sheep", StringComparison.OrdinalIgnoreCase))
    {
        return "sheep";
    }
    else if (result.Equals("leaf", StringComparison.OrdinalIgnoreCase))
    {
        return "leaves";
    }
    else if (result.Equals("thief", StringComparison.OrdinalIgnoreCase))
    {
        return "thieves";
    }
    else if (result.Equals("potato", StringComparison.InvariantCultureIgnoreCase))
    {
        return "potatoes";
    }
    else if (result.EndsWith("y", StringComparison.InvariantCultureIgnoreCase) &&
        !result.EndsWith("ey", StringComparison.InvariantCultureIgnoreCase))
    {
        // Don't pluralize "by"
        if (result.Length > 2 && !result.EndsWith(" by", StringComparison.InvariantCultureIgnoreCase))
        {
            result = result.Truncate(result.Length - 1) + "ies";
        }
    }
    else if (result.EndsWith("us", StringComparison.InvariantCultureIgnoreCase))
    {
        // http://en.wikipedia.org/wiki/Plural_form_of_words_ending_in_-us
        result += "es";
    }
    else if (result.EndsWith("x", StringComparison.InvariantCultureIgnoreCase))
    {
        result += "es";
    }
    else if (!result.EndsWith("s", StringComparison.InvariantCultureIgnoreCase))
    {
        result += "s";
    }

    return result;
}

Chris continued, "naturally, this was the only usage of this otherwise highly useful function. We could have easily utilized this function to pluralize things like foots, tomatos, boies, wifes, and etc.!"




Categories: Computer Humor | Computers | Humor | Programming | Technology | The Daily WTF
Article :: The iOS 5 Developer's Cookbook: Building Your First Project

This chapter introduces you to the basics of using Xcode to build your projects. You see how to build a simple Hello World project, compile and test it in the simulator, and then learn how to compile for and deploy to the device. You also discover some basic debugging tools and walk through their use as well as pick up some tips about handy compiler directives. This chapter also looks at how to submit to the App Store and perform ad hoc distribution for testing.

Categories: Computers | InformIT | InformIT Programming | Programming | Technology
Don't Rely Solely On jQuery's "keyup" Event

A few days ago I pushed some changes to the form validation up to my WatchMeCode website. I was trying to fix a scenario where a browser cache would have some of the data in the purchase form already filled … Continue reading 

Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Article :: Software [In]security: BSIMM versus SAFECode and Other Kaiju Cinema

Gary McGraw and Sammy Migues clarify the intended use of the Building Security In Maturity Model (BSIMM) and compare it to the SAFECode Practices methodology.

Categories: Computers | InformIT | InformIT Programming | Programming | Technology
Article :: David Chisnall Presents a Developer's Reading List

Expert programmer David Chisnall provides a list of the 5 books he believes every programmer should read.

Categories: Computers | InformIT | InformIT Programming | Programming | Technology
CodeSOD: Globally Coupled

"I work on a team maintaining a large and enterprisey PHP system," writes Amber, "and as such, my job mostly involves doing enhancements and fixing bugs."

"It sounds normal enough, if not for the fact that almost all variables are globals and each of them might or might not be initialized in the same way, or the same place, as seen in this screenshot."

"That's tolerable, but the real problem arises when I need to reuse a function in a different location. I've added line breaks and formatting to make some sense of things..."

global $dbCon;
  $dbCon->InitOpen($cf_db, 'db1');

.... snip a few hundred lines ....

function getRanking () {

  global $dbCon, $dbCon_test, $dbCon2, $cf_db;
  include '../rtuser/rtutil.php';
  $dbCon_test->
  InitOpen($cf_db, 'db2'); 

  ..... snip ....

  /* rt_rank() requires $dbCon as db connection to testdb
   * in this context, $dbCon currently points to Db1 thus
   * temporarily pointing $dbCon to testdb is necessary (fred)
   */

  $tempdbConDb1 = $dbCon;
  //assign $dbCon_test to $dbCon to have testdb connection
  $dbCon = $dbCon_test;       
  
  $memcacheKey = 'hof_ranking_' . $cntr . ':' . $offset;
  
  //call rtutil.php's getrtRank()
  // cache db r in memcache for 5 minutes
  $r = unserialize(getMemCache($dbCon2, $memcacheKey, '5 minute', 'getrtRank', $args));                                                      

  //swap back $dbCon so that the code relying on $dbCon pointing to Db1 won't be affected
  $dbCon = $tempdbConDb1;      

  include '../rateuser/rateutil.php';

  ... snip ...

  /* rate_rank() requires $sql as db connection to testdb
   * in this context, $sql currently points to gm thus
   * temporarily pointing $sql to testdb is necessary (fred)
   */

  $tempSqlGm = $sql;

  //assign $sql_test to $sql to have testdb connection
  $sql = $sql_test;       
  $memcacheKey = 'hof_ranking_' . $cntr . ':' . $offset;
  
  //call rateutil.php's getRateRank()
  $result = unserialize(getCacheInfo($sql2, $memcacheKey, '5 minute', 'getRateRank', $args));
  list($uidlist, $nicks, $votes, $imageIds, $genders) = $result;                                                      

  //swap back $sql so that the code relying on $sql pointing to gm won't be affected
  $sql = $tempSqlGm;      
//....
}

Amber continues, "what happened here was that, in file A, a global database link identifier pointed to database 1 but in the include file B, the same variable was supposed to point to database 2. What I did was to swap out the link identifier whenever a function in file B was involved, then swap back whenever a function in file A was involved. Injection was not an option as the Globals were so deeply and variably coupled that decoupling them needs to be done on a case-by-case basis. And that was just one place...




Categories: Computer Humor | Computers | Humor | Programming | Technology | The Daily WTF
Article :: Economics of Software Quality: An Interview with Capers Jones, Part 2 of 2 (Podcast Transcript)

Rex Black and Capers Jones continue discussing Capers Jones' book The Economics of Software Quality. Watch this podcast to learn some surprising and motivating facts about software quality and how to improve it.

Categories: Agile Programming | Computers | InformIT | InformIT Agile Programming | Programming | Project Management | Technology
Classic WTF: Rutherford, Price, Atkinson, Strickland, and Associates Dentistry, Inc

I'm at CodeMash today (stop by the Inedo booth if you're there!), so I thought it'd be a great time for this classic. Rutherford, Price, Atkinson, Strickland, and Associates Dentistry, Inc was originally published on January 30th, 2008.


Dr. Rutherford July 19th, 2004 marked a new chapter in New Portlandopolis’s rich dentistry history. It was on that day that the bitter rivalry between Dr. Rutherford, DDS; Dr. Price, DMD, DDS; Dr. Atkinson, DMD; and Dr. Strickland, DDS/DDS-PhD, had finally come to an end. Though there’s much debate on what exactly started the feud, everyone knows what brought the dentists together: the nationwide “denta-corps” that can out-price, out-service, and out-anything their small, family dental practices.

Although the partnership talks had begun years before, July 19th was their agreed-upon D-Day, wherein the four separate practices would officially combine to be Rutherford, Price, Atkinson, Strickland, and Associates Dentistry, Inc. In the months leading up to D-Day, and after much bickering and debate, the four dentists got everything ready from new signage to new logoed toothbrushes. The only thing that remained was combining their computer systems. That task was left to Aaron B, an IT consultant who had the pleasure of working with each office through many of the “ugly years.”

Fortunately for Aaron, each of the dentists used the same practice management system: Beaglesoft’s Practice EnterprisePlus. It certainly wasn’t the best software, but it was among the most expensive. Perhaps more-importantly, Beaglesoft offered all sorts of outrageously-priced add-ons that the dentists could buy to one-up one another. For example, a wand-shaped oral camera required a $7,000-per-site “camera driver,” in addition to the ungodly amount the camera cost in the first place. When Aaron plugged the camera into his laptop (which didn’t have any Beaglesoft software running), it was recognized as a plug-and-play camera and immediately started streaming video. Not that it mattered though; as soon as Dr. Price had his installed, the other three dentists had to get one as well. 

“While our prices might seem high,” a Beaglesoft rep once told Aaron, “keep in mind that you’re paying for quality. Our products are rigorously tested to work in today’s and tomorrow’s high-tech dental office.”

And for that reason, Aaron wasn’t too worried about Beaglesoft’s portion of the D-Day migration. They assured him on several occasions that their latest and greatest – Beaglesoft Practice EnterprisePlus Elite with Networking – could network a “virtually unlimited” number of practices. The four Aaron was linking together was “chump change” compared to what the system could do.

When Friday, July 16th – the weekend before D-Day – had finally come, the dentists were ready. They closed their offices at noon and, per Beaglesoft’s instructions, initiated the migration process. Over the next twelve hours, so the plan went, each practice’s system would upload its data to the Central Server at Dr. Strickland’s office. Naturally, none of the other dentists were too thrilled about having a “Central Server”, especially one at Dr. Strickland’s.

Aaron arrived at Dr. Strickland’s office early Saturday morning to find a surprising message on the server: “Migration Completed Successfully.” He ran through some initial smoke tests and it appeared that the migration did, in fact, complete successfully. After a trip to the other three dentist offices, Aaron verified that he could access any patient’s file from any office. He called up the four dentists to share the good news: come Monday, they should be in business.

Monday came and, shortly thereafter, the four offices were out of business. The system had completely grinded to a halt. Every click of the mouse was met with a several-minute delay, and every delayed response was met with more clicking. Aaron, who happened to be on-site “just in case,” immediately suspected the newly-installed T1 lines.

Aaron called up the phone company. They ran a few diagnostics on their end, only to find that each office’s T1 line was completely pegged. Most certainly, the technician claimed, the problem was on their end. Perhaps a router gone haywire?

Aaron checked and rechecked the switches, the hardware, the ports, and the routers. He rebooted once, twice, and thrice. Everything seemed functional, aside from the fact that the Central Server was firing packets off non-stop.

Not sure what else to do, Aaron bridged his laptop between the Central Server and its switch. Within seconds, he logged hundreds of megabytes of data, far too much for anyone to go through in the middle of such a crisis. He had no choice but to take the “satellite” dentists offline to investigate the problem. They grew suspicious of this and, of course, Dr. Strickland, and demanded that there was foul-play involved.

With only a couple users accessing the Beaglesoft system, Aaron was able to get a handle on the traffic. As he assuaged the other dentists over the phone, Aaron noticed that a lot of the data seemed to be coming from SQL Server. Specifically, it was from queries like this:

 SELECT * FROM Patients

Digging further, Aaron figured out that, whenever a user wanted to look up a patient, the program would run “SELECT * FROM Patients” query, returning the entire Patients table to the client computer.

What’s worse, the query would run any time a character was typed in the patient search box. Searching for just his first name – A-A-R-O-N – resulted in five SELECT * queries.

What’s still worse, the same method of client-side filtering was used for appointments. It wouldn’t just get, say, today’s appointments. Or this week’s. Or, say, any that haven’t happened yet. It would query for every appointment that they ever had or would have in the future. That’s about 100,000 rows.

And since each appointment involved a patient, it’d have to fire off queries for each appointment to download and filter information about the patient.

It was apparent that Beaglesoft’s “rigorous testing” of “Practice EnterprisePlus Elite with Networking” involved, perhaps, a single computer and two, maybe three patient records. He immediately called Beaglesoft to report their issues and a demand a resolution.


(an actual screenshot from Beaglesoft’s install directory)

Within a few hours, three of Beaglesoft’s finest were on a plane to New Portlandopolis. When they arrived, two of them split off to work on “de-migrating” the system into the original four databases. The other Beaglesoftie, a product manager, worked on “damage control” – and boy did she have a lot of damage to control.

By that time – ten hours into Rutherford, Price, Atkinson, Strickland, and Associates Dentistry, Inc’s first day – the dentists were at each other’s throats. Dr. Price blamed the mess on Dr. Strickland who was “online the entire time, ” while Dr. Strickland was convinced that Dr. Atkinson had somehow “spiked the T1s,” while Dr. Rutherford believed that Dr. Price “wanted to retire, and was bringing everyone else down.” Eventually, Dr. Atkinson stormed out and tore down the new "Rutherford, Price, Atkinson, Strickland, and Associates Dentistry, Inc" sign. As he stomped the sign into pieces, he vowed never to work together again. Things pretty much went downhill from there.

After things cooled down a bit with the dentists, the product manager met with Aaron. Angered that his future prospects looked like a repeat of the “ugly years”, he lambasted Beaglesoft’s latest and greatest, and asked why, oh why, they couldn’t have done some client-side caching. Or, at the very least, use the magical WHERE clause.

She was astonished by Aaron’s technical knowledge and eagerly asked more questions on “WHERE clauses and other optimization techniques.” Near the end of their conversation, she actually offered Aaron a job as a Lead Developer at Beaglesoft.

Aaron ended up declining the position. He figured that they’d never be willing to tar and feather the existing development staff. That, and after the Beaglesoft Fiasco of 2004 (as it’s called today), he’d have a lot of cleaning up and intra-dentist diplomacy to do. Besides, how could he miss taking part in the latest exciting chapter in the dentistry history of New Portlandopolis?




Categories: Computer Humor | Computers | Humor | Programming | Technology | The Daily WTF
Article :: Vacationing in Java

This lesson looks at sites that feature Java programs and talks about the history and development of the language.

Categories: Computers | InformIT | InformIT Programming | Programming | Technology
Article :: Software [In]security: vBSIMM Take Two (BSIMM for Vendors Revised)

Gary McGraw and Sammy Migues introduce a revised, compact version of the BSIMM for vendors called vBSIMM, which can be thought of as a foundational security control for vendor management of third-party software providers.

Categories: Computers | InformIT | InformIT Programming | Programming | Technology
Article :: Languages, Verbosity, and Java

With the new spate of programming languages emerging for the Java virtual machine and other platforms, it's more important than ever that the rules of a language make code clear and concise. But clarity and conciseness don't exactly go hand in hand. Dhanji R. Prasanna compares some of these new languages with a popular mainstay, Java, contrasts their expressiveness, and explains why Java is verbose for a reason.

Categories: Computers | InformIT | InformIT Programming | Programming | Technology
Article :: Programming in Objective-C

To help you understand the steps involved in keying in a program and compiling and running it, this chapter shows you how to write your first simple Objective-C program.

Categories: Computers | InformIT | InformIT Programming | Programming | Technology
Sketchy Skechers.com

Imagine yourself as an eager, young developer. After many long months of self-study, you’ve carefully honed your craft and have skillfully mastered virtually all development technologies from enterprisey to hipster. Your twelve-page résumé could land you a job anywhere, and as it would happen, the job you decided to take was at a highfalutin consultancy filled with like-minded developers who were almost as skilled as you.

You and you cohorts could build anything. Literally, anything: a software cure for cancer; a software cure engine that could dynamically load cure plug-ins at runtime to cure anything; or even a software engine factory that could dynamically create engines that could dynamically load plug-ins that could do anything.

And as it so happened, your virtually unbounded skillset was desperately needed to solve an otherwise unsolvable problem: build skechers.com. The requirements for the shoe company’s website were mind-bogglingly complex: retrieve product information from some enterprisey ERP system, format it prettily on the web, and let people place orders online.

Although no one in the history of software development had ever undertaken a project of such scale, you were prepared for anything. In fact, even before hearing what the website would be for, you had already spec’d-out the architecture: use XML-based XSL to transform server-generated XML into XHTML and JavaScript.

Hopefully now you can appreciate the mindset that the developer(s) of Skechers’ website must have had. Their masterpiece can be seen by a simple view-source of skechers.com:

That’s the XML data sent by the server when visiting http://skechers.com/. Your browser then spends a bit of time transforming into HTML and JavaScript using the following XSL:

While the idea of building a website like this in XML and then transforming it using XSL is absurd in and of itself, digging through the code is a treasure trove of WTF. I’m sure there are at least three levels of Hell that are more pleasant than having to maintain this JavaScript-generating XSL code:

 <script type="text/javascript">
	var skxProduct = {}; var skxStyle = '<xsl:value-of select="$style/@code"/>';
	<xsl:for-each select="$style/product">
	  skxProduct['<xsl:value-of select="@color"/>'] = {
	  color: '<xsl:value-of select="@primary-color"/><xsl:if test="@secondary-color">
		/ <xsl:value-of select="@secondary-color"/>
	  </xsl:if>',
	  images: [
	  <xsl:for-each select="media">

		<xsl:sort data-type="number" select="@view"/>
		<xsl:if test="position() &lt; 7">
		  '<xsl:value-of select="@image"/>'
		  <xsl:if test="position() != 7">,</xsl:if>
		</xsl:if>
	  </xsl:for-each>
	  ],
	  inventory: [
	  <xsl:for-each select="sku">
		<xsl:sort data-type="number" select="@pos"/>

		{
		size: '<xsl:value-of select="@size"/>',
		<xsl:if test="@type">
		  type: '<xsl:value-of select="@type"/>',
		</xsl:if>
		stock: '<xsl:value-of select="@in-stock"/>',
		<xsl:if test="@disc">
		  disc: '<xsl:value-of select="@disc"/>',
		</xsl:if>
		price: '<xsl:value-of select="@price"/>',
		upc: '<xsl:value-of select="@upc"/>'
		}
		<xsl:if test="position() != last()">,</xsl:if>

	  </xsl:for-each>
	  ]
	  };
	</xsl:for-each>
  </script>

I shudder at the thought of how labyrinthine the server-side code generating this must be.

I’ve preserved (well, after some indentation/formatting) some of the files for posterity. Just right-click download, then view in your favorite text editor for best experience.

I’m sure there’s plenty more fun examples to be found at all levels of skechers.com; feel free to share them in the comments or send them to me if you think they’d deserve an article of their own.




Categories: Computer Humor | Computers | Humor | Programming | Technology | The Daily WTF
Article :: Exploring the Mythical Weekend Coding Project

Did you ever spend a weekend working through some kooky idea for coding an app you'd had in mind for years? Like many of us, Dhanji R. Prasanna has carried concepts around in his mental pockets, and one day he decided to go ahead and try it. The goal was a working app in two days. Would he succeed or fail miserably? Some things he learned were to be expected, but others he could never have predicted.

Categories: Agile Programming | Computers | InformIT | InformIT Agile Programming | Programming | Project Management | Technology
Article :: The iOS 5 Developer's Cookbook: Building Your First Project

This chapter introduces you to the basics of using Xcode to build your projects. You see how to build a simple Hello World project, compile and test it in the simulator, and then learn how to compile for and deploy to the device. You also discover some basic debugging tools and walk through their use as well as pick up some tips about handy compiler directives. This chapter also looks at how to submit to the App Store and perform ad hoc distribution for testing.

Categories: Agile Programming | Computers | InformIT | InformIT Agile Programming | Programming | Project Management | Technology
InformIT: The Trusted Technology Source for IT Pros and Developers

As I mentioned in my previous post, I'm doing a write up of our AJAX conventions and how they're paying off for us. In this series of posts, I'm going to cover a few topics: The AjaxContinuation Clientside Continuations (this … Continue reading 

Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Coded Smorgasbord: Schizophrenic Haiku Comments and More

"I found a schizophrenic comment that either intentionally or unintentionally happens to be a haiku," wrote Ben Vanik, "svn blame says this single line is the work of 3 different people across 3 years of coding."

// should delete the temp files here, no cannot because, we havent read it in yet!

 

"I'm modifying some firmware for a product that has a serial connection," Fahrzin Hemmati writes, "this was found in the method that translates the incoming data into useful bytes."

//Clear it, or it, smack it, flip it, rub it down 
//(Oh nooooo...)		
mem[iAddress] &= ucClearBit;
mem[iAddress] |= ucAssignBit;

 

"How do you feel when you see this code on the first day of your job?" wonders Ritesh

#define EIGHTY 256

 

"I found this piece of java code in our corporate directory," writes Peter S, "two of our JUnit test classes end in this method. I do not know if these were intended phuns/easter eggs."

@Test
public void testNothing() {
   assertTrue("Assert just to keep JUnit happy!", true); }

 

"When debuging some client code I came across this," wrote Blair, "tmpnum8 was wrong. Now I just have to figure out what all the other tmpnums are..."

tmpnum6 = tmpnum2 + tmpnum * (tmpnum4 - tmpnum2);
tmpnum7 = tmpnum3 + tmpnum * (tmpnum5 - tmpnum3);
tmpnum8 = tmpnum6 + tmpnum1 * (tmpnum7 - tmpnum6);

 

"The previous developer on our OBIEE environment had some interesting ways of developing queries," wrote Bart, "not only did he not know about Oracle functions like NVL(), requiring him to write everything using lengthy CASE statements, also using joins seemed out of the question. This code is een excerpt from a _large_ view unioning large blocks of codes like this to eachother. I also like how he did code reuse, he copied large pieces of code to different views."

SELECT decode(authorization_kd,
 3,3,    4,3,    6,3,    7,3,    34,3,
 55,3,   57,3,   58,3,   24,4,   10,4,
 11,4,   21,4,   71,4,   36,4,   37,4,
 38,4,   13,4,   14,4,   84,4,   53,4,
 15,4,   33,4,   31,4,   32,4,   09,5,
 12,6,   52,6,   54,7,   19,8,   20,8,
 79,8,   99,8,   9) process_kd
FROM   dossier
WHERE  authorization_kd NOT IN (1, 30, 35, 85, 86, 87, 16, 17, 18)

 

"Starting a work in a project is always a kind of challenge," notes Wiadran, "if the project is developed for years and written mostly in ASP classic... it might become a nightmare. Nevertheless, projects developed for years have some bright side as well: parts of not-understandable code and commentaries."

For intI = 7450 To 7450
'Now lets go and create the f*&ker
   ... snip...
Next 

 

Jimmi found yet another wrapper for the illusive '!' operator.

private static bool InvertBool(bool org)
{
	bool returnValue = false;
	if (org)
	{
		returnValue = false;
	}
	if (!org)
	{
		returnValue = true;
	}

	return returnValue;            
}

 

"How many naming conventions can you find in the following line of code?" writes Malcom

StandardResponse UnSubscribeNewsletterUserAccount(
  string opTinGUID,string email, 
  string sellingRegion, string source, 
  DateTime opt_out_date, string strevent, string reason);

 

"While diving through some old code I'm maintaining, I found this jewel," Frank writes from the Submit-To-WTF Visual Studio Add-In, "Not only is this snippet a part of a rather intricate XML merge system, but it also merges the XML by string operations. To add insult to injury, the XML is not possible to define in a schema (as elements have to occur in certain patterns, while the name of the only valid elements in the XML 'schema' is either FLD or REC. The types of REC depends on the NAME attribute, and it is the NAME attribute that ultimately decides the order of the REC elements in the document. In other words, a truly fubar mess."

// Dear future developer(s): 
// I have no idea who actually came up with such a glorious violation of the 
// XML definition, but legacy systems being legacy systems means that we can't 
// switch this. 
// I feel for you, young padawan; I'd rahter kiss a wookie than mess with this.
if (line.IndexOf("REC NAME=\"Hovednivå\"") <= -1) continue;

 




Categories: Computer Humor | Computers | Humor | Programming | Technology | The Daily WTF
Article :: Fluent Visual Basic: The Visual Studio UI

Rebecca Riordan discusses how Visual Studio helps you manage a development project with Solutions and Projects, and then takes a closer look at the UI and how to configure it to suit the way you work.

Categories: Computers | InformIT | InformIT Programming | Programming | Technology
Speaking at San Diego DNUG tonight

If you're in the San Diego area tonight, I'll be giving my talk on domain modeling. Details below: http://www.sandiegodotnet.com/ I've been told that there is free pizza. If not, I might be able score some stale bagels from my hotel's … Continue reading 

Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology