Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I see the DataManager in some Xamarin apps being set up with a get?

My application is set up like this:

public partial class App : Application
{

    public static DataManager db;

    public App()
    {
        InitializeComponent();
        MainPage = new MainPage();
    }

    public static DataManager DB
    {
        get
        {
            if (db == null)
            {
                db = new DataManager();
            }
            return db;
        }
    }

Can someone explain to me the advantage of setting up the DataManager in this way vs:

    public App()
    {
        InitializeComponent();
        MainPage = new MainPage();
        db = new DataManager();
    }
like image 800
Alan2 Avatar asked Dec 11 '22 08:12

Alan2


1 Answers

A lot of people do not like static global variables. They try and replace them with concrete instances of classes instead.

What they should really be doing is to create an interface for each class and use dependency injection to provide the classes. This will then allow unit testing and proper separation of concerns. Using an MVVM pattern is also a good idea.

This can be a large change though for a lot of people and is often requires a new mind-set.

like image 129
Steve Chadbourne Avatar answered May 10 '23 23:05

Steve Chadbourne