Tuesday, July 1, 2008

Why you shouldn't just wrap simple code in a try-catch

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/why_you_shouldnt_just_wrap_simple_code_in_a_trycatch.htm]

Structured programming languages, like C#, provide a try-catch ability to wrap an entire block of code, and catch if anything goes wrong. This can massively simplify error checking, especially when calling external components. However, like any good thing, it can also be abused. During interviews, or rushing out code, many developers resort to using try-catch as a quick way of doing error checking, but there's a catch (excuse the pun). For example, consider this trivial method to sum up an array of integers:

 

    public static int GetSum(int[] aInt)
    {
      int intSum = 0;
      foreach (int i in aInt)
      {
          intSum += i;
      }
      return intSum;
    }

 

You can crash this code, such as by passing in null for the int array.  To blindly wrap a simple method with try catch, just to catch normal logic errors like null variables or indexOutOfRange, has problems.

  • For performance, Try-catch is enormously expensive compared to an if-then check. It could be hundreds of times slower. So it's bad design to use a try-catch for something trivial when an in-then will do just file, like checking if a variable is null.

  • What will you do in the catch statement? Some devs may say "I'll log my exception info here" - but what info is that... that the developer didn't bother to do basic error checking?

  • It makes the usability worse. Perhaps instead of re-throwing an exception, or logging and going to the global error page, the method could have used an if-then to return a sentinel value instead. For example, perhaps a string manipulation method could just return the original value (or null) if the input parameters were invalid.

  • It loses context. Say your code catches a null exception - that thrown exception doesn't tell you what variable was null. You've lost context and information with which to fix the code. Using an in-then would have given you full access to all the local variables and their context.

  • It makes all exceptions equal - a null or indexOutOfRange exception (things that are easy to catch with if-thens) are put on the same level as a critical outOfMemory error - i.e. both trigger the catch block. This in turn can distract the maintenance team, who gets swamped with tons of exceptions, most of them preventable.

  • Perhaps worst of all, it implies that the developer isn't thinking about how their method can fail. Rather than understanding the code and what it does, they just wrap it all in a try-catch, and move on. This means they could have not coded for valid use cases.

Try-catch has obvious benefits, but it has limitations and consequences too. There are times when it's much more beneficial to explicitly catch the error conditions with an if-then instead.

Monday, June 30, 2008

The problem with "I'll wait until my manager sends me to training"

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/the_problem_with_ill_wait_until_my_manager_sends_me_to_tra.htm]

With all the new technologies coming out, many software developers want to get sent to training seminars. Sometimes "Training" is fun - your company spends thousands of dollars to send you to a fancy building, during regular working hours, where you have an in-person expert guide you through some marketable skill. It lets you feel like you're part of an elite group, and on the insider track. Usually these sessions even provide free snacks!

This is great - until a developer uses it as an excuse for inaction, as in "Rather than learn technology XYZ on my own, I'll wait until my manager sends me to training." For the vast majority of mainstream development technologies and techniques (C#, SQL, JS, HTML, XML, security, performance, automation, etc...), such thinking has some big problems.

  • Because live training seminars are expensive, managers are very reluctant to send you.

  • If you're truly motivated, usually there are free (or cheap) alternatives instead. For example, there may be free user groups that meet in your area that offer presentations on hot topics. Sometimes there are even free MSDN events. Worst case, you can buy the $50 book.

  • Therefore, by the time management is willing to sink $3000 to send you to a training seminar, you could probably learn it faster yourself via some other method.

Having special training for a cutting edge technology or proprietary tool is great. But a motivated developer shouldn't need to wait to be sent to training before learning C#, or how to improve code performance because that information is already freely available in many other formats besides in-person training seminars.

 

Sunday, June 29, 2008

Silverlight TruckWars 2.0 - Migrated to SL2 Beta 2

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/silverlight_truckwars_20___migrated_to_sl2__beta_2.htm]

I migrated Silverlight TruckWars to the SL Beta 2. I started working on TruckWars as a way to learn Silverlight back in the Alpha last year. Being a Microsoft product, there have been two more betas (with plenty of breaking changes), but I've finally migrated it.

 

Things of note - Beta 1 started supporting buttons, which obviously simplified things. For example, it helped me remove keyboard input. It also had some subtle changes that affected the gameplay. Also, there still is no dropdown. Before I was using an HTML dropdown to select the levels. Rather than jump through hoops, I just ceded the dropdown part until the next release.

 

Because the code has been migrated from an alpha, to a beta, to another beta, it's becoming pretty screwy. Not the best, most agile code out there, but good for a demo of what cool stuff Silverlight can do. You can play it here.

 

Friday, June 27, 2008

The first LCNUG meeting - Windows Workflow Foundation

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/the_first_lcnug_meeting__windows_workflow_foundation.htm]

The first LCNUG meeting occurred this past Thur, June 26. It went well - about a dozen (very talented) people. Scott Seely presented on Windows Workflow Foundation, which you can download from the website. The small number of attendees (as compared to the hundred who normally attend larger groups) allowed more community interaction and networking. Overall, a good success for the kickoff meeting of a new group. I'm proud that Paylocity can help sponsor this.

 

Tuesday, June 24, 2008

Do you have time to blog?

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/do_you_have_time_to_blog.htm]

I enjoy blogging, so I encourage others to try and enjoy it too. I've met many people who say they'd like to blog, but "just don't have the time." I understand that we're all busy. I figure a single blog post can be small, with a few paragraphs, much like a big email. And, an average blog may have 2-3 posts a week. So, if you can cut out just one pointless email, every other day, then you'll have enough time to blog. And if you blog about what you're actively working on, then it's much faster, because the words, concepts, and code snippets are already at the tip of your tongue. Optimistically, there are ways to squeeze blogging into one's life.

Monday, June 23, 2008

Minimalist Code Samples

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/minimalist_code_samples.htm]

A minimalist code sample is a snippet that demonstrates a specific purpose, requires no extra context, yet can still run. For example, doFactory.com explains design patterns with a "real-world" sample, and a "structural" (i.e. minimalist) sample. Because it abstracts out the context, the minimalist sample has several benefits:

  • Easier to apply: It is easier to apply to different contexts - such as new projects.

  • Easier to remember: It is much smaller (no context means less code), therefore it's easier to remember what the code was about. For example, I have a folder essentially called "LearningSnippets", where I categorize different coding tricks. By keeping all the snippets small, they're fast for me to physically load, "mentally load", and then run. The last thing I want is to dig through some 2000 line project, scratching my head, thinking "how did I do that sorting algorithm?"

  • Easier to learn: It's easier to learn new concepts. Removing the irrelevant context means there's less to get distracted by, so you can focus on the specific concept that you care about.

  • Easier to show others: It is easier to show to others, such as a newsgroup, where other developers don't care about the business context. I sigh when I see some poor guy post a 5 page code question on a forum, because few people will sift through all that.

  • Easier to enhance: It can be much easier to enhance because the code is not constrained by some rigid business context.

  • It is a courtesy to others: If you just care about a 3-line algorithm, it would be long-winded of me to hide that behind hundred of lines of business context and plumbing.

In .Net, many errors come down to a few bad lines of code - you've got the wrong method, a bad input parameter, or some syntax error. It becomes very convenient when working with others, or learning new concepts, to be able to isolate code down to the minimalist sample.

Friday, June 20, 2008

Natural Language Processing

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/natural_language_processing.htm]

I got very bad marks in grammar during middle school. It wasn't until after I graduated public school that I cared about writing, and hence grammar. Now, I find it quite fascinating, so I was interested to read about a CodePlex project - SharpNLP. In their own words:

SharpNLP is a collection of natural language processing tools written in C#. Currently it provides the following NLP tools:

  • a sentence splitter

  • a tokenizer

  • a part-of-speech tagger

  • a chunker (used to "find non-recursive syntactic annotations such as noun phrase chunks")

  • a parser

  • a name finder

  • a coreference tool

  • an interface to the WordNet lexical database

So, you could type in a paragraph, and it parses that out into the different sentences, and then different words and parts of speech. Of course, I began to think if maybe this could be extended to be like the FxCop of technical articles. For example, according to the Microsoft Manual of Style for Technical Publications, the rules to merely capitalize a sub-title are non-trivial - there are 10 rules and it takes a full page to explain them. I wonder in theory if you could have a NLP (Natural Language Processing) tool run through a subtitle (as an input string), and apply the rules, much like you can parse a arithmetic expression for correct syntax. I was starting to toy around with it, but it seemed to quickly get difficult, so maybe I look at it another day.

 

In the meantime, if you're interested in NLP, check out SharpNLP.