logoalt Hacker News

HumanOstrichlast Thursday at 2:53 AM2 repliesview on HN

I was glancing around and landed on the page for the flyweight pattern.[1]

It looks like `addBook` is using the spread operator, which always creates a shallow copy of the book instance properties, thus nullifying any benefits of the flyweight pattern. It also attaches extra arbitrary properties, but still assigns the result to a `book` variable. I don't think this is a great example.

[1]: https://www.patterns.dev/vanilla/flyweight-pattern/

Edit: I forgot to give you kudos for all the effort it must have taken to create all this content, and I appreciate that you're making it available for free.


Replies

KPGv2last Thursday at 4:19 AM

> which always creates a shallow copy of the book instance properties, thus nullifying any benefits of the flyweight pattern

No, the opposite: it highlights the benefits of the flyweight pattern. The shallow copy saves memory. That's the point. You have two identical books. Rather than wasting memory with a deep copy, you make a shallow copy, where all your props point to locations in memory where values are located, and then you modify whatever is different. Now your shallow copy only consumes a small bit of extra memory.

And if those props are all primitives, then you can then modify that shallow copy, and it won't affect the original.

show 1 reply
songodongolast Thursday at 11:24 AM

Good to know I wasn’t the only one thinking “wait a second…” when reading that one and seeing the spread operator being used.