Have banned methods return a new Immutable instance instead
See original GitHub issueHi,
I love the fact that this library is super small and that doesn’t try to do anything else than making your data immutable 😃.
There’s only one thing holding me back from using it though:
Immutable([3, 1, 4]).sort()
// This will throw an ImmutableError, because sort() is a mutating method.
Have you considered returning a new immutable structure with the sorted array instead? (the same applies for every other banned method).
Thanks 😃 Darío
Issue Analytics
- State:
- Created 9 years ago
- Comments:11 (4 by maintainers)
Top Results From Across the Web
How can we maintain Immutability of a class with a mutable ...
In Employee class, return the deep clone copy of the address instance in the getAddress() method instead of returning original instance.
Read more >rtfeldman/seamless-immutable - GitHub
Returns a mutable copy of the array. For a deeply mutable copy, in which any instances of Immutable contained in nested data structures...
Read more >Immutable Set in Java - Baeldung
Let's suppose we have a HashSet instance with some values. Making it immutable will create a “read-only” version of our set.
Read more >Immutable Data Patterns in Dart and Flutter - Dart Academy
Factories work a lot like static methods, in that they must explicitly return an instance of the class instead of doing so automatically...
Read more >Writing Immutable JavaScript in 2022 - /dev/solita
This means that toUpperCase method did not mutate the original string, instead it returned a new modified copy. The same thing happens if...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I considered it, but the trouble is that doing this can mask bugs. For example:
If you change that first line to be
Immutable([3, 1, 4])
, what should happen?Currently
array.sort()
throws an exception, letting you know that some code that made sense with a mutable array no longer makes sense. If insteadarray.sort()
just returns a sorted, immutable array, then now an unsorted array will be returned here, and you have a bug to track down - a potentially nasty one, if there is a lot of logic surrounding this code.I prefer this API because you can take an immutable array and write any number of helper functions that return sorted ones, but the only way to make bugs like this easy to find is to override the mutable methods to throw an exception. 😃
You can add method
sorted(fn)
that returns sorted copy of array.