Home > Software engineering >  Best practice to call a variable from ViewModel
Best practice to call a variable from ViewModel

Time:07-05

I have this variable in my ViewModel:

private String chosenDay;

and when I want to set the chosen day I use setter function:

public void setChosenDate(String date){
        chosenDay = date;
    }

and when I want to use it,I use getter:

public String getChosenDay(){
        return chosenDay;
    }

My question is: Do you think its a good practice to use getter and setters for the viewModel or I can just access the variable directly from the activity?

viewModel.chosenDay = "Monday"

Thank you !

CodePudding user response:

It really depends on how you want to write your code. If you wish to follow OOP principles yes your example is the right way. You are doing "Encapsulation".

Encapsulation is one of the four fundamental OOP concepts.

Benefits of Encapsulation:

  • The fields of a class can be made read-only or write-only.
  • A class can have total control over what is stored in its fields.

CodePudding user response:

Storing the variable inside your ViewModel sounds like a better approach to me: when you rotate the screen, all the variables stored in the Activity will get cleared and you'll need to handle their restoration manually (onSaveInstanceState -> onCreate).

But that's not the case with view models (generally) as they are intended to survive such transitions hence the value will preserve its state with no extra effort.

And I think there's some "ideological" reasoing behind storing the state in ViewModels/Presenters: it's usually considered a good practice to minimize the amount of code and state stored in the UI layer (Fragments, Activities, etc.)

CodePudding user response:

Your ViewModel is used to handle data required by your views, or you want to collect data from network calls to show them to the user in Activity/Fragment, if you have a specific case where you want to save chosenDate to use it maybe in another Activity/Fragment, you can use setters and getters, to get and set the date to use it in another Activity/Fragment by using Share ViewModel's else also you can use it for one Activity/Fragment it all depends on your use case.

  • Related