⬆️ ⬇️

Null, great and terrible

Design error



This is exactly the same way: null in C # is a uniquely erroneous solution, thoughtlessly copied from earlier languages.



  1. The worst thing is that the universal traitor can be used as the value of any reference type - null, to which the compiler does not react. But at the time of execution it is easy to get a knife in the back - NullReferenceException . It is useless to handle this exception: it means an unconditional error in the code.
  2. Pepper to wound: failure (NRE when trying to dereference) can be very far from the defect (use null where a full-fledged object is waiting).
  3. Plump fur animal: null is incurable - no future innovations in the platform and language will save us from the leper inherited code, which is physically impossible to stop using.


This Pandora box was opened during the creation of the ALGOL W language by the great Hoar , who later called his own idea a billion-dollar mistake.



The best historical alternative



Of course, it was, moreover, it was obvious by modern standards.



  1. Unified Nullable for significant and reference types.
  2. Nullable dereferencing only through special operators ( ternary -?: , Elvis -?. , Coalesce - ?? ), providing for the mandatory processing of both variants (presence or absence of an object) without throwing out exceptions.
  3. Examples:

    object o = new object(); //   -  
    object o = null; //   -  ,   null 
    object? n = new object; // nullable  -  
    object? n = null; // nullable  -  
    object o = n; //   -  ,  object  object? 
    object o = n ?? new object(); //   fallback  (coalesce),       n != null
    Type t = n ? value.GetType() : typeof(object); //    - value   n,    null
    Type? t = n ? value.GetType(); //    ? -  null,    null,       ,   nullable
  4. NRE : null , .


, . , .





, . .



  1. null if. .



    1. , — .
    2. , ,
    3. (, )
    4. .


  2. NotNull.



    1. R#
    2. , : null , .


  3. Null object. , .



    1. null , : IEnumerable, , , .. — -.
    2. : — null null object, : , NRE .


  4. . .



    1. , null, . , , .



    2. .


  5. null: , Try OrDefault . . .



  6. CanBeNull. - NotNull.



    1. R#
    2. , NotNull
    3. null .


  7. C# (, , coalesce)



    1. null .
    2. ArgumentException null NotNull .
    3. .
    4. , .


  8. Optional. .



    1. NRE
    2. .
    3. , , .
    4. memory traffic


  9. Maybe. LINQ , .



    1. .
    2. Optional .
    3. , .
    4. - .


  10. .



    1. , .
    2. Code Contracts , .
    3. , --.


  11. Fody/NullGuard. null .



    1. : , , , .
    2. AllowNull — , — .
    3. , null, AllowNull
    4. , .
    5. .
    6. ( null , ).
    7. , , null, .
    8. — NullGuard .
    9. , , .


  12. null ( C#)



    1. .
    2. NRE .
    3. , ,
    4. .
    5. .






— :



4, 5, 7, 11, 12 ( )1, 23, 6, 8, 9, 10


20 , .





.



')

Source: https://habr.com/ru/post/309462/



All Articles