Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

More on Bad Ways to Set Up Commands in Your View Model

DZone's Guide to

More on Bad Ways to Set Up Commands in Your View Model

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

Last week I wrote about a bad way to set up commands in your view model. This prompted a few comments and strong opinions.

My main intention with the post was originally to rally against creating properties with a private setter when they will only ever be set once and the code that does the setting is kept apart from the property. All things being equal, I'd rather maintain code that looks like my preferred code than the first example.

I do, however, appreciate that this is not optimal in all situations. I've just spent lots of time working with code that does trivial things in the command or are executed occasionally, and so the overhead of creating a new command each time it's needed is not an issue.

For the avoidance of doubt, I'm perfectly fine with any of the following when used at an appropriate time. 

public class MyViewModel : ViewModelBase
{
    private RelayCommand myCommand;
 
    public RelayCommand MyCommand
    {
        get
        {
            if (myCommand == null)
            {
                myCommand = new RelayCommand(() =>
                {
                    // some functionality here
                });
            }
 
            return myCommand;
        }
    }
}

or

public class MyViewModel : ViewModelBase
{
    private RelayCommand myCommand;
 
    public RelayCommand SaveCommand
    {
        get
        {
            if (myCommand == null)
            {
                myCommand = new RelayCommand(this.Save);
            }
 
            return myCommand;
        }
    }
 
    private void Save()
    {
        // do something
    }
}

and I've used both in the past.

Anyway, moving on...

Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:

Published at DZone with permission of Matt Lacey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}