开发者

Should a custom comparer for strings allow for null values

开发者 https://www.devze.com 2023-02-22 09:47 出处:网络
I\'m looking at someone elses code for a custom comparer that compares strings. I\'m noticing that it will fall over if at least one of the string parameters is null.

I'm looking at someone elses code for a custom comparer that compares strings.

I'm noticing that it will fall over if at least one of the string parameters is null.

The compare returns -1, 0 or 1 based on the result of the comparison.

Should code like this be fixed to handle nulls and if so what should it return if one of the 开发者_如何学运维parameters was null?


According to the remarks section of the IComparer.Compare Method (MSDN)

Comparing null with any type is allowed and does not generate an exception when using IComparable. When sorting, null is considered to be less than any other object.

I.e. the following seems sensible:

  • If they are both null, return 0
  • If x is null but not y, return -1 (x < y)
  • If y is null but not x, return 1 (x > y).


The answer will/should ultimately be a result your business requirements.

Likely the code was written to a certain set of requirements, and nulls weren't part of the consideration.

It should be fixed if:

  • your business requirements need it
  • you ever have the remote chance of the inputs being null
  • you're handling defects because of it
  • multiple components are leveraging this functionality


I guess it depends on the purpose of the comparer, but I would lean toward changing the comparer to throw an exception if one of the strings is null. It seems to go against the purpose of the comparer, which is to return whether one string is greater than, equal to, or lesser than the other string. Null doesn't fit into that set.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号