Is “If” condition better than ?? and casting

佐手、 提交于 2019-12-22 03:49:04

问题


I have following two approaches for same functionality - one with "if” condition and one with "?? and casting". Which approach is better? Why?

Code:

  Int16? reportID2 = null;
  //Other code

  //Approach 1
  if (reportID2 == null)
  {
       command.Parameters.AddWithValue("@report_type_code", DBNull.Value);
  }
  else
  {
     command.Parameters.AddWithValue("@report_type_code", reportID2);
  }

  //Approach 2
  command.Parameters.AddWithValue("@report_type_code", ((object) reportID2) ?? DBNull.Value);

UPDATE

Based on the answers, following are the benefits of ??

  1. Increased readability
  2. Decreased branching deapth of program flow (reduced cyclomatic complexity)

Note: Cost of casting as object is negligible.

REFERENCE

  1. Null-Coallescing Operator - Why Casting?

回答1:


I always use null-coalescing operator in such cases:

command.Parameters.AddWithValue("@name", value ?? DBNull.Value);

command.ExecuteScalar() as int? ?? -1;

etc.

It increases code readability, decreases branching depth. Also was created especially for database-related scenarios such as ADO.NET.




回答2:


The null coalescing operator (??) is a better approach because it does the same thing as your initial block but in a single, easy to read line. This makes the code more readable and more maintainable.

This is one of many examples of syntactic sugar, that is to say code statements which are "shortcuts" for representing a commonly-used idea.i++ is another example of this, as it replaces i = i + 1. It is cleaner and simpler, just like ??.




回答3:


In your example, approach 2 is better. You should not repeat yourself, and apprach 1 has the code and the parameter name twice. If you want to change the paramater name, you should do so on two places, and this is a hassle.

The real code to compare this to is this:

object value = DBNull.Value;
if (reportID2 != null)
{
    value = reportID2;
}
command.Parameters.AddWithValue("@report_type_code", value);

If you use this or the ?? operator is a matter of personal preference. I think the if is more clear, especially because you need parenthesis and casting in the case of the coalesce operator.




回答4:


I'd prefer the ?? operator. Although brevity does not always lead to better readability, in this case it does because as a reader you don't have to compare what is equal and what is different between the two lines of the if and else. Furthermore, you eliminated duplication of code (which is always good!). Consider the case you rename your database field name @report_type_code. Then you only have to alter it at one place.



来源:https://stackoverflow.com/questions/13698421/is-if-condition-better-than-and-casting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!