re: From classes to plain objects and pure functions VIEW POST


Well done, exploring a more functional approach!

There may be an issue with your use of the word "pure," both in the title of this article and in the hybrid docs. Either it's unclear how hybrids uses pure functions, or the term "pure" isn't accurate and is best left out. As it is, the term left me confused, and I'll attempt to explain why.

Per Wikipedia and others, a function must meet two criteria to be pure: idempotency (which you have) and 0 side effects.

Here's the first function used as an example in the Hybrid docs:

export function increaseCount(host) {
  host.count += 1;

This function isn't pure because it mutates host. Here's one way to get similar functionality from a pure function:

export function increaseCount(oldCount) {
  return oldCount + 1;

Or, perhaps more usefully…

function increaseCount(oldHost) {
  return Object.assign(
    { count: oldHost.count + 1 },

In your place, I'd either remove the term "pure", or update the docs to explicitly demonstrate how hybrids takes advantage of functional purity.

None of this should be taken as feedback on the system itself. The approach you offer is intriguing. Bravo!


Thanks for the comment! In hybrids pure function term relates mainly to the property descriptor methods (get and set), where you don't mutate host element - it is only used to get dependencies.

Obviously, connect method is not pure - it is created especially for side effects, like adding event listeners. However, for the user of the library, the definition can be a simple object with values and pure functions - and usually, it is, when you use built-in factories or created by yourself.

The increaseCount from the example is a side effect in some way (not technically) - it is a callback attached to the button - it is not an integral part of the definition of the custom element.

Hybrids is a UI library for creating Web Components, which favors plain objects and pure functions over class and this syntax.

This is the first sentence of the docs. As you can see, it means, that library favors pure functions, not require to use them. Also, there is no statement, that all of the functions should be pure :)


Ah, that last point is subtle. Some of my confusion came from having skimmed over the code samples in the docs trying to find an example that showed pure functions in use, and didn't find any.

Not a complaint, mind you. Just sharing a perspective in case you feel it makes sense to more explicitly demonstrate the ways in which hybrids promotes the use of pure functions. The other part — about how it demotes class and this syntax — is clear from the docs as-is…and that's something I really like about what you've done!

Thanks for your thoughtful reply. :)

code of conduct - report abuse