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.

2 comments to Bad programming examples (part 1 of x)

  • should it not be

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

  • Lucas

    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.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>