Skip to content

Instantly share code, notes, and snippets.

@pmatatias
Last active December 28, 2023 02:49
Show Gist options
  • Save pmatatias/3e5cf6cf54c8d57af014c70580fb9965 to your computer and use it in GitHub Desktop.
Save pmatatias/3e5cf6cf54c8d57af014c70580fb9965 to your computer and use it in GitHub Desktop.

Mutable Class https://gist.github.com/pmatatias/a87bc52f1c766780270d7653e0428cee

  • Non-final Variables: In a mutable class, variables are not declared as final. This allows their values to be changed directly after the object's creation.

  • Direct State Manipulation: You can modify these variables directly from anywhere in the app, including the UI. For example, calling friendList.removeLast directly modifies the internal state of the object.

  • Potential Issue: The risk here is that if you change the state directly without properly notifying the UI (like using notifyListeners() in Flutter), the UI might not update to reflect this change. This can lead to inconsistencies and hard-to-track bugs, especially in more complex applications.

Immutable Class https://gist.github.com/pmatatias/fff47dc09b53e1ea94a3ed889ebba383

  • Final Variables: In an immutable class, all variables are declared as final. This means once an instance of the class is created, the values of these variables cannot be altered.

  • Updating via Methods: To change the state, you don't modify the variables directly. Instead, you define methods that create and return a new instance of the class with the updated values. For example, to remove a friend, you'd have a method like removeLastFriend which returns a new instance of the class with the updated friends list.

  • Why It's Immutable: It's called immutable because the original instance of the object does not change. Instead, every change results in a new object. You're not updating values directly from the UI; you're requesting a new object that reflects the desired changes.

Conclusion

  • Immutable Approach: It's not just about using final but also about the pattern of avoiding direct manipulation of the object's state. Instead, you always work with methods that return a new instance representing the new state. This pattern is beneficial for maintaining a predictable and consistent state, especially in reactive frameworks like Flutter.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment