What's wrong with this code?(ekampf.com)

submitted by ekampfekampf(3195) 4 years, 7 months ago

First post in a series of "What's wrong with this code" snippets...

5 comments |category: |Views: 2

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by senfosenfo(881) 4 years, 6 months ago 0

Here is an example of a singleton. No locks necessary. I would have posted in your blog, but I kept getting an error.

http://senfo.blogspot.com/2007/07/singleton-design-patter-in-c.html

Reply

posted by tortustortus(25) 4 years, 6 months ago 0

That's not a good example.

A property should be used for the accessor, not a method. That's what properties are for.

As it stands, it does need locks to avoid race conditions should multiple threads be accessing the same singleton at once. That implementation can lead to multiple instances of the singleton being created.

Reply

posted by offwhiteoffwhite(975) 4 years, 6 months ago 0

My code would use a private method to instantiate the singleton with an attribute which handles the locking. It would look like...

// requires using System.Runtime.CompilerServices
[MethodImpl(MethodImplOptions.Synchronized)]
private void InstantiateSingleton()
{
if (_singleton != null)
{
_singleton = new Singleton();
}
}

The attribute handles the locking for you and then the property access is much simpler.

public static Singleton Instance
{
get
{
if (_instance == null)
{
InstantiateSingleton();
}
return _instance;
}
}

The code is then also self-documenting with the descriptive method name.

Reply

posted by offwhiteoffwhite(975) 4 years, 6 months ago 0

That != should be ==

Reply

posted by ekampfekampf(3195) 4 years, 6 months ago 0

Hi,
Thanks for the comments, check out the summary at http://www.ekampf.com/blog/2007/07/15/WhatsWrongWithThisCode1Discussion.aspx

Regards,
Eran

Reply

information Login or create an account to comment on this story