Easy syntax to indicate a method mutates
See original GitHub issueI was surprised by the introductory chapter “Updating arrays and objects”. What attracted me to Svelte is that it uses its position as a compiler to identify mutations and cascade them efficiently, e.g. by rewriting assignments and parsing expressions to identify their dependencies. Why give up on methods?
The chapter offers two workarounds, but surprisingly recommends rebuilding arrays and objects as “more idiomatic”. Again, one of the points I liked from the Rethinking Reactivity talk was that Svelte tries to eliminate the redundant computation that plagues other frameworks. Rebuilding an array where only one element changed is an example of largely redundant computation. Yes, some people prefer the “everything is immutable” approach, and I do too - in a language like Haskell where the compiler rewrites those constructions into mutations. I don’t expect Svelte to perform the necessary analysis to safely rewrite these constructions, but if I choose to use mutable values I do expect Svelte to identify those mutations.
In fact, this workaround wasn’t mentioned in the original issue proposing this chapter for the tutorial. Instead, it proposed the second workaround, an identity assignment, e.g. array = array
. @Conduitry says that, with Svelte, it “will get compiled away and trigger an update.” Great! That’s what I want. That’s the efficiency I was looking for with Svelte. I just don’t want to have to write that whole assignment.
I believe a third way is possible: a special syntax for function calls that identifies the method as mutating. For example, array.push!(element)
. I don’t particularly care too much about the exact syntax, just that it is less verbose than an assignment, and that it is part of the mutating expression.
Considering that mutating methods can mutate their arguments in addition to their this
context, perhaps a general “this variable will be modified by this expression” syntax is in order, e.g. schema.validate(object!)
.
[1]: If Svelte can see all the code, then I think it should be able to identify mutating methods. A method mutates an argument arg
(including the implicit argument this
) if:
- It is one of a handful of built-in methods identified as mutating (e.g.
Array.push
) - It assigns to a property of or calls another method that mutates
arg
(either directly or through an alias)
Identifying these mutations properly, including alias analysis, is a big lift, which is why I’m happy to settle for just special syntax.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:9 (3 by maintainers)
Simpler than a single trailing character? I guess we’ll have to agree to disagree on that one.
This is not really simpler than
array = array
, which is a concept that every user has to learn already (since reactive assignments are at the core of Svelte), and which does the same thing.