Viewing entries in
Development

Comment

Weekly Training - Debugging in Visual Studio 2008

I recently had a few of the junior and work experience developers asking for some help in solving some coding issues.

More often then not the answer was in front of them but they didn’t know about tools such as Quick Watch, Navigating through code, Breakpoints and the Callstack window.

I decided it was time to get back to basics and show them all the tools they can use to find and solve the issues themselves.

Comment

Comment

Concise Code - Does it make things hard to read?

I was using Resharper 4 and noticed some nice code cleanup advise that it gives. One to note it the compression of:

// Create job if quote is won
if (CurrentQuote.Status == "A")
{
    quoteView.FindControl("btnCreateJobCard").Visible = true;
}
else
{
    quoteView.FindControl("btnCreateJobCard").Visible = false;
}

To the one liner (which I prefer)

// Create job if quote is won
quoteView.FindControl("btnCreateJobCard").Visible = CurrentQuote.Status == "A";

I like short succinct code. I think the shortened form is better, but I know some people need to do a double take to see what it’s trying to do.

I would love to hear your opinions on this.

Comment

Comment

Use TryParse instead of Parse

I noticed something in the code of the project I was currently working on. It manifested itself in a crash with exception type FormatException. The problem was caused by the developer using code like this:

double percentComplete = Convert.ToDouble(tbProgress.Text);

or

double percentComplete = double.Parse(tbProgress.Text);

The problem with this is that there are potential exceptions lurking if the string value is null or malformed (which was the case)

Instead of just coding like the above the developer should have at least tried to catch the exception like so and handle it (in this case it was best to give back a default value of 0):


double percentComplete;
try
{
    percentComplete = double.Parse(tbProgress.Text);
}
catch (FormatException)
{
	// Handle the error or return a default value
    percentComplete = 0;
}

To be an good developer you should use TryParse instead

double percentComplete = 0;
if (!double.TryParse(tbProgress.Text, out percentComplete))
{
    // Handle the error
}

In the situation above, I didn’t need to handle the error as I wanted to return a default value of 0 if it couldn’t parse it. So the following would have sufficed:

double percentComplete = 0;
double.TryParse(tbProgress.Text, out percentComplete);

Why is TryParse better?

Remember, exceptions are expensive to deal with. So avoid it if you can.

Other resources

Comment