Is “If” condition better than ?? and casting

2019-04-21 00:03发布

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?

4条回答
再贱就再见
2楼-- · 2019-04-21 00:33

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-21 00:40

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.

查看更多
虎瘦雄心在
4楼-- · 2019-04-21 00:50

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.

查看更多
你好瞎i
5楼-- · 2019-04-21 00:54

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 ??.

查看更多
登录 后发表回答