Bad programming examples (part 1 of x)

There’s no end to the number of bad programming examples we’ve seen in the past or will see in the future. Recently, I saw this one. (This was actual code seen in an actual project.)


try { createDate = Request.Params["createDate"]; }
catch (Exception) { createDate = "-1"; }

Nice and ugly. Aside from a horrible way to implement a try/catch block, it screams of performance issues and unreadable code.

A more proper alternative follows.


createDate = Request.Params["createDate"] ?? "-1";

The same project also had this use of integer parsing.


try { myInt = Int32.Parse(textBox.Text); }
catch (Exception) { myInt = -1; }

In this case, you would use the TryParse method instead:


if (Int32.TryParse(textBox.Text, out myInt))
    myInt = -1;

Exception handling is for exceptions, not for null checking or validations.

Bookmark and Share

Popularity: 13% [?]

Related Posts

Life cycles around and nothing adds comfort more than a cold wet nose snugging to your heart.

-- Robert Palmer

Comments 2

  1. travis wrote:

    should it not be

    if(!Int32.TryParse(textBox.Text, out myInt)
    myInt = -1;

    Posted 25 Apr 2008 at 1:32 pm
  2. Lucas wrote:

    Someone should start a wiki of fundamental dos and don’ts, to help newcomers (and oldcomers) grasp some basic concepts.

    Btw, what’s going on in the first example? Can this throw an exception?
    Request.Params["createDate"]

    If an exception is thrown when “createDate” is not found, then your solution won’t work well ;) If null is returned, then createDate would never be assigned “-1″ anyway.

    Posted 25 Apr 2008 at 4:30 pm

Post a Comment

Your email is never published nor shared. Required fields are marked *