Why you should never use code from MSDN

I think part of the problem with bad code is the habit to copy/paste samples from MSDN.

For example, consider this example.

Explanatory Comments

image

I agree that Microsoft should put explanatory comments into the code – the code is a sample on how to do something.   The problem is that someone who doesn’t know better will copy/paste the entire block into their solution.  I think Microsoft could help its developers by putting a provision at the top of the sample:

image

The cynic in me would then expect to see that warning also copy/pasted into someone’s project.  Perhaps the copy/paste button on the page could filter the comments.

Big Blocks Of Code

Another problem with the MSDN code “as-is” is that the code is one big block – there are three classes put into 1 block.  It wouldn’t kill Microsoft to put each class into their own block.  The MSDN explanations could then be broken up and when you copy/paste the code, you only get 1 class at a time.  As it stands, all of the explanations is in 1 big paragraph at the top of the 1 big code sample.  A step by step approach might be more helpful – and promote better code.

Constructor Chaining

Finally, MSDN doesn’t chain the constructors of the example. 

public UrlConfigElement(String name, String url)
{
    this.Name = name;
    this.Url = url;
}

public UrlConfigElement()
{

    this.Name = "Contoso";
    this.Url = "http://www.contoso.com";
    this.Port = 0;
}

Should be

public UrlConfigElement(String name, String url)
{
    this.Name = name;
    this.Url = url;
    this.Port = 0;
}

public UrlConfigElement()
    : this("Contoso", "http://www.contoso.com")
{
    
}



That is just sloppy coding and should be fixed…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: