What’s wrong with this code? #2

.NET, Development, What's wrong with this code? September 2nd, 2007

Check out the following code snippet:

    static decimal Division(int a, int b) { return a / b; }

kick it on DotNetKicks.com

Comments (7) imported from www.ekampf.com/blog/:

Sunday, September 02, 2007 9:46:22 AM (GMT Daylight Time, UTC+01:00)

divide with zero..

bb king

Sunday, September 02, 2007 10:54:57 AM (GMT Daylight Time, UTC+01:00)

Absent casting to decimal in return.

HaGever

Sunday, September 02, 2007 2:18:37 PM (GMT Daylight Time, UTC+01:00)

Casting has nothing to do with it. The code compiles and runs without exceptions unless you divide by zero as specified in the first comment.
But division by zero is not the only thing wrong here…

Eran Kampf

Sunday, September 02, 2007 4:28:29 PM (GMT Daylight Time, UTC+01:00)

1 in 5 Americans can divide by 0, such as. Just ask Miss South Carolina.

Brennan Stehling

Sunday, September 02, 2007 6:06:58 PM (GMT Daylight Time, UTC+01:00)

2Eran Kampf
Casting necessary here!
Define
a = 3
b = 2
Without casting your result will be 1, but with casting - 1.5
Int/Int return int, but (decimal)int/int = decimal
P.S.I don’t remind a division inasmuch as that this is trivial.
;-) Good luck

HaGever

Sunday, September 02, 2007 6:40:16 PM (GMT Daylight Time, UTC+01:00)

Exactly!
You found the second point I was aiming at - dividing integers results an integer. so given a=1 and b=2 the method will return 0 and not 0.5 as expected.
On your first comment I understood you want to cast the return value which means doing (decimal)(a/b) which is still wrong.
You need to cast a and b before dividing by doing (decimal)a / (decimal)b or by doing what you said in the second comment (decimal)a / b which actually casts a to decimal and then divides it by b.
I guess the 2nd snippet was too easy compared to the 1st :\
Regards,
Eran

Eran Kampf

Friday, November 23, 2007 9:23:52 AM (GMT Standard Time, UTC+00:00)

This is great! One question: Is there any way around the authentication issue? I have a portal which requires a login/password. Am I out of luck? –thanks

WOW GOLD

What’s wrong with this code? #1 - Discussion

.NET, Development, What's wrong with this code? July 15th, 2007

The Singleton implementation in the snippet I posted works fine as a lazy, thread-safe Singleton as it ensures only one thread can create the instance. However, there’s a big performance hit caused by the fact that we acquire a lock each time the Singleton’s instance is requested. Yoav, suggested to fix this performance problem by checking for null twice - outside the lock and inside the lock:

public static Singleton Instance
{
    get
    {
        if (Singleton._insatnce == null)
        {
            lock (_syncRoot)
            {
                if (Singleton._insatnce == null)
                {
                    Singleton._insatnce = new Singleton();
                }
            }
        } return Singleton._insatnce;
    }
}

This code, known as “Double-Check Locking” doesn’t work in the presence of either an optimizing compiler or shared memory multiprocessor. The main reason for this (as explained by Brad) is that the CLR’s memory model allows non-volatile read\writes to be reordered as long as that change cannot be noticed from the point of view of a single thread. This means that the compiler can reorder write to _instance during initialization and its construction write, causing another thread to see _instance as set even though it wasn’t initialized yet (appears on stress testing). To prevent such optimizations we can declare _instance to be volatile or by explicitly specifying a memory barrier before accessing the data member using System.Threading.Thread.MemoryBarrier(). Using Thread.MemoryBarrier() is more efficient than volatile as it allows compiler optimization when barrier is not required:

public static Singleton Instance
{
    get
    {
        if (Singleton._insatnce == null)
        {
            lock (_syncRoot)
            {
                if (Singleton._insatnce == null)
                {
                    Singleton newInstance = new Singleton(); // Ensure all writes used to construct new value have been flushed.  System.Threading.Thread.MemoryBarrier(); Singleton._insatnce = newInstance; // publish the new value
                }
            }
        } return Singleton._insatnce;
    }
}

Another way of doing the same thing is using System.Threading.Interlocked.CompareExchange() which also enforces a memory barrier.

Omer, suggested creating the instance of Singleton in the static constructor (which is guaranteed to be thread-safe) rather than in the Instance accessor. While in this implementation you lose some of the flexibility of controlling exactly at which point in time the Singleton instance is created, this kind of control is not really required in most cases and giving up on it allows making the code shorter and less confusing…

kick it on DotNetKicks.com

What’s wrong with this code? #1

.NET, Development, What's wrong with this code? July 9th, 2007

I decided to start a new column gathering all sorts of “what’s wrong with this code?” snippets. Why?

  1. Its fun.
  2. Its good for interview questions.
  3. It starts discussions. More interesting than just talking (or writing) to myself.

So, here’s what I plan:

  1. I post a code snippet (most probably C# but I’m not setting constraints on myself)
  2. You comment on what’s wrong with the code on the snippet
  3. I post my answer, interesting comments, etc. (you can comment on my answer too :-))

* Note that these posts are syndicated on blogs.microsoft.co.il (and maybe some other places) so please leave your comments at the main blog - www.ekampf.com/blog/ ** I know there are many “What’s wrong with this code?” out there already. I’ll try not to recycle (too much ;)) When looking at these snippets note the following “Bad Code” classifications: Confusing code, Overly complex code, Performance Issues, Buggy. So, to start with an easy one (I think), check out the following Singleton implementation:

public sealed class Singleton
{
    private Singleton() { } 

    private static Singleton _insatnce;
    private static object _syncRoot = new Object();

    public static Singleton Instance
    {
        get
        {
            lock (_syncRoot)
            {
                if (Singleton._insatnce == null)
                {
                    Singleton._insatnce = new Singleton();
                }
                return Singleton._insatnce;
            }
        }
    }
}

Update July 16th, 2007: I’ve posted the answer and a summary on the comments at the following post.

kick it on DotNetKicks.com

Tags: ,