mercredi 28 novembre 2018

Is a public static DateTime field an anti pattern or a good practice?

In our program we have so called WallclockDateTime. Because we can shift in time, this WallclockDateTime is not related to the current time. But now I need this WallclockDateTime everywhere in my classes.

First I decided to pass this WallclockDateTime by reference from constructor to constructor. But that takes a lot of maintenance. And now I have some class Foo which is created in masses in a Collection<Foo>, and passing this same WallClockTime over and over again through the constructor seemed a bit useless to me. So I thought: Can't this be done more efficient?

First I tried to make the central WallclockDateTime static. But the OnPropertyChanged() is from outside my solution. If I make _wallclockDateTime public and static I can get to it everywhere! But it seems dirty to me. So what is a good solution for this? Passing from constructor to constructor? Or make the field public and static? Or some other clever solution?

    private DateTime _wallclockDateTime;
    public DateTime WallclockDateTime
    {
        get
        {
            return _wallclockDateTime;
        }
        set
        {
            if (_wallclockDateTime != value)
            {
                _wallclockDateTime = value;
                OnPropertyChanged(nameof(WallclockDateTime));
                OnPropertyChanged(nameof(CurrentSliderStateLabel));
                OnPropertyChanged(nameof(WallclockDateTimeTicks));
            }
        }
    }

// This class is used in a Collection<Foo>
public class Foo
{
    private static DateTime _wallClockTime;

    public Foo(ref DateTime wallClockTime)
    {
        _wallClockTime = wallClockTime;
    }

    public void Bar()
    {
        // Do something with the _wallClockTime
    }
}

Aucun commentaire:

Enregistrer un commentaire