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

后端 未结 13 1758
谎友^
谎友^ 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.

提交回复
热议问题