When I learned TCA, I had a hard time understanding why Reducer is called Reducer. Just recently I watched the Point-Free episode where they explain their reasoning and I find it kind of far-fetched or at least not very intuitive. They basically state they named it Reducer because of it's similarity to the reduce method in Swift. To name things in a consistent manner compared to Swift features seems to be a good approach overall, but I feel the ergonomics of the Reducer isn't similar enough to the reduce method or at least it's not apparent intuitively.
Let me elaborate more why I don't see enough similarity. Here's the reduce functions API:
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
In words: The reduce function is defined on collections (e.g. Array), takes the initial value to build the result from and a closure that incrementally alters the initial value into the final value. It returns the final value once all alterations are completed.
Now let's have a look at the Reducer types API:
public init(_ reducer: @escaping (inout State, Action, Environment) -> Effect<Action, Never>)
In words: The Reducer type takes one argument, a reducer closure. This closures takes the current state, action and environment as arguments and returns a "side effect" object which will basically cause a new call to the same closure if not .none.
Here's all the differences between reduce and a Reducer:
- The
reducefunction is defined on collections, for aReducerno collection is involved anywhere. - The
reducefunction takes the initial value for its result as the first argument, theReducertakes the current value (state) though, this is an entirely different concept (more in line withmap). The idea of the "initial state" lies in an entirely different place, in the Store to be exact, but not in theReducer. - The
reducefunction completes and returns the final result, whereas theReducerclosure or type never returns with a final result, only applies "the next result". There's no concept of "completion" involved.
These are the reasons why I think the similarity to reduce is far fetched and what makes new developers also not make the connection. While the State and Action, also for the most part Store and Environment are intuitive names, the Reducer feels more like the place where we handle what needs to happen when actions are triggered to me. Hence I‘m thinking that ActionHandler would be a more intuitive and clear name. I think it might help mitigate some of the confusion for new developers learning TCA.
Looking forward to your thoughts and opinions. Feel free to suggest other names as well.