Why test against null in this example?

Igor Cheglakov

I follow this tutorial on commands in MVVM:

https://metanit.com/sharp/wpf/22.3.php

Here's an example code of a Command from the tutorial

private RelayCommand addCommand;
public RelayCommand AddCommand
{
    get
    {
        return addCommand ??
            (addCommand = new RelayCommand(obj =>
            {
                Phone phone = new Phone();
                Phones.Insert(0, phone);
                SelectedPhone = phone;
            }));
    }
}: 

As I understand the logic, we have a private backing field addCommand and public property AddCommand which only has a getter. In said getter the field addCommand is tested against null. If addCommand != null then its value is returned. Otherwise a new exemplar of RelayCommand class is returned. But since AddCommand doesn't have a setter, including a private one, doesn't it mean addCommand field will always return null? Why test against null a field that will always return null? Why keep such a field at all?

Caius Jard

You might be missing the part in C# where any assignment returns the value that was assigned, as a result

x = 1

Returns 1

This means you can do

y = x = 1

And y ends up as 1 too, because the result of x=1 is 1 and this is assigned to y

As a result the pattern you see offers a one time creation of a value for your addCommand; if addCommand has a value then the existing value is returned, if it does not (i.e. it is null) then the ?? ensures the right hand side is executed which performs an assignment: addCommand receives a new value, which is then returned as the "result of the assignment" (and ultimately is returned as the result of the get). This addCommand then survives to the next time it's called, meaning that the creation of it is only done once, and upon first demand rather than by default upon creation of the enclosing class (we call it lazy loading/lazy instantiation..)

private int x = null;

//if x is not null return x otherwise return: (assign 1 to x and return 1)
get { return x ?? (x = 1); }  

Footnote:

You might consider refactoring your code as:

get
{
    if(addCommand == null){
        addCommand = new RelayCommand(obj =>
        {
            Phone phone = new Phone();
            Phones.Insert(0, phone);
            SelectedPhone = phone;
        }
    }

    return addCommand;
}

It's not significantly longer, and it's equivalently performant, so if you'd have understood it better, then the time it saved you in not having to ask on SO about it would forever be profit :) - sometimes C# devs can go too far in the quest for finding some compact, one-line way to express intent and end up with something that is equally "computer readable" but less "human readable", and if you can't understand it at a glance it might well be a needless waste of your time every time you come to look at it

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Why is ArrayAdapter always null in this example?

From Dev

Why we need test cases to run against plain POJOs

From Dev

Why is this XPath test against child text contents failing?

From Dev

Why would the example test in Laravel fail for redirect?

From Dev

Unit Test against ActiveMQ

From Dev

Testing RegEx against Null

From Dev

Checking against null in Equals()

From Dev

If the null-coalescing operator is supposed to protect against null values, why would Visual Studio or ReSharper suggest a possible null solution?

From Java

Why there is no ConcurrentHashSet against ConcurrentHashMap

From Dev

double negation to check against not NULL

From Dev

Checking against JSONObject returning null

From Dev

Why does an empty dataframe fail an is.null() test?

From Dev

Why the result of my test is null whereas I have mocked the dependency?

From Dev

Spring boot unit test by Junit 5 why mock return null

From Dev

Xcode UI Test example

From Dev

Is this HashSet test example possible?

From Dev

Xcode UI Test example

From Dev

Rails: Test against and handle ActionController::InvalidAuthenticityToken

From Dev

Test a string against a RegEx Pattern in Javascript

From Java

How to test multiple variables against a value?

From Dev

Running QuickCheck against Simple Test w/ Function

From Dev

How to test Yeoman frontend against (Spring) Backend?

From Dev

passing a URL to test against with nose testconfig

From Dev

NSubstitute Test against classes (VB.net)

From Dev

Algorithm to test minimum hamming distance against a set?

From Dev

Best methodology to test against multiple Java versions

From Dev

Powershell test-path against variable contents

From Dev

Test Q objects against model instance

From Dev

running the same test against multiple implementations

Related Related

  1. 1

    Why is ArrayAdapter always null in this example?

  2. 2

    Why we need test cases to run against plain POJOs

  3. 3

    Why is this XPath test against child text contents failing?

  4. 4

    Why would the example test in Laravel fail for redirect?

  5. 5

    Unit Test against ActiveMQ

  6. 6

    Testing RegEx against Null

  7. 7

    Checking against null in Equals()

  8. 8

    If the null-coalescing operator is supposed to protect against null values, why would Visual Studio or ReSharper suggest a possible null solution?

  9. 9

    Why there is no ConcurrentHashSet against ConcurrentHashMap

  10. 10

    double negation to check against not NULL

  11. 11

    Checking against JSONObject returning null

  12. 12

    Why does an empty dataframe fail an is.null() test?

  13. 13

    Why the result of my test is null whereas I have mocked the dependency?

  14. 14

    Spring boot unit test by Junit 5 why mock return null

  15. 15

    Xcode UI Test example

  16. 16

    Is this HashSet test example possible?

  17. 17

    Xcode UI Test example

  18. 18

    Rails: Test against and handle ActionController::InvalidAuthenticityToken

  19. 19

    Test a string against a RegEx Pattern in Javascript

  20. 20

    How to test multiple variables against a value?

  21. 21

    Running QuickCheck against Simple Test w/ Function

  22. 22

    How to test Yeoman frontend against (Spring) Backend?

  23. 23

    passing a URL to test against with nose testconfig

  24. 24

    NSubstitute Test against classes (VB.net)

  25. 25

    Algorithm to test minimum hamming distance against a set?

  26. 26

    Best methodology to test against multiple Java versions

  27. 27

    Powershell test-path against variable contents

  28. 28

    Test Q objects against model instance

  29. 29

    running the same test against multiple implementations

HotTag

Archive