In your opinion what is more readable: ?? (operator) or use of if's

后端 未结 13 1719
谎友^
谎友^ 2021-01-21 07:05

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 ha

相关标签:
13条回答
  • 2021-01-21 07:38

    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.

    0 讨论(0)
提交回复
热议问题