Skip to content

Best Practices

Travis Truttschel edited this page Apr 17, 2022 · 6 revisions

State Classes

  • Do use properties instead of fields.
    • Fields are not supported.
  • Do use public getters for properties.
    • Using properties with backing fields might break updates.
  • Do use private setters for properties.
    • Using private setters prevents accidental mutations.
  • Do keep state classes concise feature focused.
    • Keeping state classes small and feature focused improves organization and efficiency.
  • Do use read-only value/enumerable types.
    • Using read-only types prevents state mutations.
  • Don't use public setters.
    • Public setters allow state to be mutated.
  • Don't use overly broad state classes.
    • Overly broad state classes will result in less efficient rebuilds due to their size and number of observers.

Good Example

public class CurrentUser
{
  public int Id { get; private set; }
  public string FirstName { get; private set; } = "Unknown";
  public IEnumerable<string> Permissions { get; private set; } = new List();
}

Bad Example

public class GlobalState
{
  public int _currentUserId { private get; set; }
  public string CurrentUserFirstName { get; set; } = "Unknown";
  public List<string> Permissions { get; set; } = new();

  public int CurrentUserId => _currentUserId;
}

State Updates

  • Do use bulk updates whenever more than one property needs to be updated.
    • In order to reduce the number of times observers are invoked.
  • Don't update state from within an observer for the same state/property.
    • A state update from within an observer for the same state/property may create an infinite circular invocation loop.
  • Don't assign properties with mutable values.
    • State values should be immutable.
Clone this wiki locally