Best syntax for a = (x == null) ? null : x.func()

后端 未结 7 789
囚心锁ツ
囚心锁ツ 2020-12-24 04:50

Basic question here - I have many lines of code that look something like:

var a = (long_expression == null) ? null : long_expression.Method();
相关标签:
7条回答
  • 2020-12-24 05:39

    I found this answer insightful.

    By doing this assignment, you are propagating the null deeper into the system. You'll have to write your null handling condition again (and again and again) to handle these propagations.

    Instead of allowing execution to continue with nulls, replace the null with a better representation (quoted from link)

    1. If the null represents an empty collection, use an empty collection.
    2. If the null represents an exceptional case, throw an Exception.
    3. If the null represents an accidentally uninitialized value, explicitly initialize it.
    4. If the null represents a legitimate value, test for it - or even better use a NullObject that performs a null op.

    In particular, replacing a null collection reference with an empty collection has saved me many null tests.

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