I'm building a tool in Flutter that allows users to edit JSON files. The application represents the JSON data as a tree of nodes. I'm considering two approaches for managing the state of the JSON data:
Immutable State
- Create immutable data structures to represent the JSON tree.
- Whenever a change is made, create a new instance of the data structure with the desired modification.
- Example:
class JsonNode { final dynamic value; final List<JsonNode> children; JsonNode copyWithChange(dynamic newValue) { return JsonNode(newValue, children); } }
Mutable State
- Use mutable data structures to represent the JSON tree.
- Directly modify the existing data structures when changes are made.
- Track mutations in a separate data structure to enable undo/redo functionality.
- Example:
class JsonNode { dynamic value; List<JsonNode> children; } class Mutation { final MutationType type; final JsonNode node; // ... other properties for tracking changes }
While immutable state is generally considered a best practice and was perfect for everything I worked on before, there could be potential benefits to using mutable state for a JSON tree editor application, such as better performance and lower memory usage for large JSON files or frequent state changes.
However, the immutable approach provides inherent benefits like easier reasoning about the code, safety, and potentially simpler implementation of undo/redo functionality.
What are your thoughts on this trade-off? Is it worth considering mutable state for a JSON tree editor application, or should I prioritize the benefits of immutability despite potential performance and memory implications? Are there any other factors I should consider when making this decision?