Skip to content

Commit

Permalink
Refactor AppData to use Lazy<T> for internal state
Browse files Browse the repository at this point in the history
Refactor AppData<T> to use Lazy<T> for internal state initialization.
Update methods in AppData.cs and AppDataTests.cs to accommodate
this change. Modify `Get` method to return `InternalState.Value`.
Adjust `QueueSave` and `SaveIfRequired` to call methods on the
current instance of app data.
  • Loading branch information
matt-edmondson committed Dec 23, 2024
1 parent 512178f commit 442bd38
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
4 changes: 2 additions & 2 deletions AppDataStorage.Test/AppDataTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ public void TestIsDebounceTimeElapsedReturnsCorrectValue()
[TestMethod]
public void TestLoadOrCreateHandlesCorruptFile()
{
var filePath = TestAppData.InternalState.FilePath;
var filePath = TestAppData.Get().FilePath;
AppData.EnsureDirectoryExists(filePath);
AppData.FileSystem.File.WriteAllText(filePath, "Invalid JSON");

Expand Down Expand Up @@ -444,7 +444,7 @@ public void TestSaveCreatesBackupIfInitialSaveFails()
[TestMethod]
public void TestLoadOrCreateRecoversFromCorruptBackup()
{
var filePath = TestAppData.InternalState.FilePath;
var filePath = TestAppData.Get().FilePath;
var backupFilePath = AppData.MakeBackupFilePath(filePath);

AppData.EnsureDirectoryExists(filePath);
Expand Down
8 changes: 4 additions & 4 deletions AppDataStorage/AppData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,12 +225,12 @@ internal static void EnsureDirectoryExists(AbsoluteDirectoryPath path)
/// Gets the current instance of the app data.
/// </summary>
/// <returns>The current instance of the app data.</returns>
public static T Get() => InternalState;
public static T Get() => InternalState.Value;

/// <summary>
/// Gets the internal state of the app data.
/// </summary>
internal static T InternalState { get; } = LoadOrCreate(); // TODO: make this a Lazy<T>
internal static Lazy<T> InternalState { get; } = new(LoadOrCreate);

/// <summary>
/// Gets or sets the last save time of the app data.
Expand Down Expand Up @@ -398,11 +398,11 @@ public static T LoadOrCreate(RelativeDirectoryPath? subdirectory, FileName? file
/// <summary>
/// Queues a save operation for the current app data instance.
/// </summary>
public static void QueueSave() => InternalState.QueueSave();
public static void QueueSave() => Get().QueueSave();


/// <summary>
/// Saves the app data if required based on the debounce time and the last save time.
/// </summary>
public static void SaveIfRequired() => InternalState.SaveIfRequired();
public static void SaveIfRequired() => Get().SaveIfRequired();
}

0 comments on commit 442bd38

Please sign in to comment.