1

I've two commands in my View Model and one of them is initialized using lazy loading and other using eager loading.

Which approach is good to go? Should I use lazy loading or eager for both?

View Model:

public class LoginPageViewModel : MvxViewModel
{
    public LoginPageViewModel()
    {
        InitializeCommands();
    }

    public MvxCommand<object> LoginCommand { get; set; }

    private MvxCommand<object> signUpCommand;
    public MvxCommand<object> SignUpCommand
    {
        get
        {
            return signUpCommand ?? (signUpCommand = new MvxCommand<object>(o => {
                ShowViewModel<SignupPageViewModel> ();
            }));
        }
    }

    private void InitializeCommands()
    {
        LoginCommand = new MvxCommand<object>(LoginUser);
    }
}

View:

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();

    var set = this.CreateBindingSet<LoginPageView, LoginPageViewModel> ();
    set.Bind (CreateAccountButton).To (vm => vm.SignUpCommand);
    set.Bind (ResetPasswordButton).To (vm => vm.ResetPasswordCommand);

    set.Apply ();
}

I'm using that within iOS app developed using Xamrian.iOS and MVVMCross

4
  • 5
    This is going to depend on what the rest of your code looks like. When do you want DoSomething to run? Is the initialisation computationally expensive? Does it use external resources? How likely is it that MyCommand will never be accessed for an instance? Etc, etc. There's no one right way to do it, it depends on the context.
    – marinus
    Commented Apr 19, 2016 at 12:47
  • they're different so they may serve for different purpose. In the second one nothing prevents the user to make multiple call to initialize() so he can "reset" the object. In the first one the (it is a singleton) new RelayCommand(p => DoSomething() ) is called only once Commented Apr 19, 2016 at 12:50
  • Incidentally, the second method isn't "eager" initialization. It's "let the client figure it out" initialization, unless you're call Initialize() yourself somewhere we can't see.
    – Ixrec
    Commented Apr 19, 2016 at 12:51
  • @marinus I've edited the question to reflect real scenario I have.
    – Adnan Umer
    Commented Apr 19, 2016 at 12:54

1 Answer 1

2

Unless you have a good reason, I would go with the simpler approach, that is, eager loading.

And, assuming you can use C# 6.0, I would try to simplify the code even more:

public MvxCommand<object> LoginCommand { get; } = new MvxCommand<object>(LoginUser);
public MvxCommand<object> SignUpCommand { get; }
    = new MvxCommand<object>(o => ShowViewModel<SignupPageViewModel> ());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.