Thoughts on life, liberty, and information technology

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 responses to “Bad programming examples (part 1 of x)”

  1. travis Avatar
    travis

    should it not be

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

    Like

  2. Lucas Avatar
    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.

    Like

Leave a reply to Lucas Cancel reply