views:

248

answers:

14

I have a method that will receive a string, but before I can work with it, I have to convert it to int. Sometimes it can be null and I have to change its value to "0". Today I have:

public void doSomeWork(string value)
{
   int SomeValue = int.Parse(value ?? "0"); //it can throw an exception(i know)
}

I did it, but my boss asked me to refactor it to:

public void doSomeWork(string value)
{
    if(string.IsNullOrEmpty(value))
        value = "0";
    int SomeValue = int.Parse(value);
}

in your opinion what is the best option?

+3  A: 

I think your best option is to do what your boss says, this one isn't worth it! That said, add a few spaces around yours and I like it better.

int someValue = int.Parse(value ?? "0");
AgileJon
A: 

In this case the earlier is more readable as its a trivial example. **However in your case they are not equivalent, as the ?? isn't the same as string.IsNullOrEmpty **

The latter would be better in cases where the if was complex. I'd say horses for courses. Just depends on the audience. Try and keep it simple.

public int doSomeWork(string value)
{
  return int.Parse(value ?? "0");
}



public int doSomeWork(string value)
{
   if(value == null)
      value = "0";
    int SomeValue = int.Parse(value);
    return SomeValue;
}
Preet Sangha
+2  A: 

I definitely prefer the null coalesce operator (??) over a series of if statements. Especially when you need to coalesce more than one value, the operator approach is FAR more readable. This plays into other newer features of C#, such as lambda expressions, LINQ sugar syntax, etc. The less code there is to muddy up the actual intentful code, the clearer the intent should/will be.

jrista
A: 

You can do it your way? Cool!

If is definitely more readable, unless everyone is more of a C# wonk than me.

John Lockwood
+1  A: 

Hi, the two options are not equivalent. A part from a bug in the second snippet (it should read if(string.IsNullOrEmpty(value)), it will handle two cases, null and empty strings, whereas the ?? operator only handles nulls.

A part from that it's way more readable. I side with your boss.

Sklivvz
+1  A: 

Another solution is

int someValue = string.IsNullOrEmpty(value) ? 0 : int.Parse(value);

Etore Marcari Jr.
+3  A: 

Personally I'd go for the corrected version of your bosses - possibly with even more checks on it - if the string's empty, yours will, as you say throw an exception, as "" isn't a well formatted number and ?? only checks for null.

Something like:

public int doSomeWork(string value) {
  int someValue = 0;

  if (!string.IsNullOrEmpty(value)) {
    Int.TryParse(value, out someValue);
  }
}

Which resolves the issue where value equals "Forty Two".

Zhaph - Ben Duguid
I didn't know I can do that! I'm sorry, i'm only a trainee
No need to apologise :)
Zhaph - Ben Duguid
+1  A: 

Your first snippet will only check if value == null, but the seconds snippet checks if value == string.Empty || value == null. I don't know what the requirements of your method is but those two snippets will do different things.

Charlie
A: 

The two aren't equivalent. If value is set to an empty string, your boss's version will work, but your version will crash.

Kyralessa
+2  A: 

Why parse the string "0" just to get integer value 0? I definitely prefer this:

public int doSomeWork(string value) {
   int someValue;
   if (String.IsNullOrEmpty(value)) {
      someValue = 0;
   } else {
      someValue = Int32.Parse(value);
   }
}
Guffa
damn, was too slow :) The link to Google Books did cost me the time ;)
Juri
+2  A: 

My refactoring would look like this

public int doSomeWork(string value)
{
   int result = 0; //default?

   if(string.IsNullOrEmpty(value))
   {
      result = 0;
   }
   else
   {
      result = int.Parse(value); //you could also consider using TryParse(...) if your string could possibly also be different from a number.
   }

   //do some calculations upon "result"


   return result;
}

I'm currently reading Martin Fowlers book on Refactoring (wanted to read it already for a longer time now) and this is what I normally prefer and I found it is also a commonly suggested "pattern" in the book.

Juri
Just one point: I wouldn't initialise the variable to zero. You can leave it uninitialised and let the compiler verify that you really set the value in both branches of the if.
Guffa
You're right. That's also why I wrote the "default?" comment because I didn't know about the calculations that should follow, but you're right.
Juri
+1  A: 

Actually you could refactor to

var value = 0;
int.TryParse(yourString, out value);

either way you always have a valid integer (if that is the goal)

Miau
+7  A: 

Why not just use TryParse()?

public int doSomeWork(string stringValue)
{
    int value;
    int.TryParse(stringValue, out value);

    return value;
}

The above code will return 0 if the value is anything but an actual number.

So in my opinion, my example is the most readable. I try to parse the int and return it. No coalesce operator, and no string methods are used. This method also handles the exceptions that might be thrown when parsing (unless you WANT the exceptions...).

SkippyFire
A: 

[Assuming you only need to check for null, and not empty string also, as others have pointed out]

The semantic difference between the two is that ?? is an expression, while if is a statement. An expression says "perform a calculation and return a result", exactly the semantics you seek. More work has to be done to allow an if statement to express the same semantics; beyond that, the if leaves room for more logic than the calculation, room you don't need.

You should use the ?? operator because it expresses exactly the desired intent.

Bryan Watts