Don’t Instantiate Then Assign

Here’s an example of some bizarre code I’ve seen recently. I’ve changed the variable names, but this is what the developer was doing.

Customer customer = new Customer();
customer = customers[response.CustomerKey];

The first line is completely unnecessary. If you instantiate an object, then assign the object to another instance, the first instance sticks around and eventually gets collected. However, there’s no reference to it. You can never use that instance. Here’s how it should look.

Customer customer = customers[response.CustomerKey];

I would assume that it was dirty code that should have been cleaned before checking into version control, except for the fact the lines were adjacent. For the life of me, I don’t know why anyone would create an unnecessary instance. Any ideas?

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted on Monday, June 15, 2009 9:10 AM

Comments on this post

# Фильмы

Requesting Gravatar...
Добрый день! Так приятно оказаться на стоящем проекте. Всем создателям респект и уважуха за ваши труды!
Left by VienexisaNice on Jun 15, 2009 2:15 PM

# re: Don’t Instantiate Then Assign

Requesting Gravatar...
Stupidity. Some people just don't get references.

Or just a refactoring mistake.

Take your pick.
Left by Michael on Jun 15, 2009 2:16 PM

# re: Don’t Instantiate Then Assign

Requesting Gravatar...
or they're not using resharper, which points out when a certain value is never used in the execution path.
Left by mihkel on Jun 15, 2009 2:56 PM

# re: Don’t Instantiate Then Assign

Requesting Gravatar...
If you look on my blog, I have blogged about the same issue before.
I find that devs that do this are lazy, non-passionate code monkeys that have no pride in the code they produce.
Left by Pieter on Jun 15, 2009 3:12 PM

# Тема епти тема

Requesting Gravatar...
Ну просто каждый пост у вас шедевр, просто дух захватывает в каждой статье, вам бы ещё пару блогов открыть не мешало!
Left by Rengenx on Feb 15, 2010 3:25 AM

Your comment:

 (will show your gravatar)