7 Staying immutable with untrusted code

 
Image

In this chapter

  • Make defensive copies to protect your code from legacy code and other code you don’t trust.
  • Compare deep copies to shallow copies.
  • Choose when to use defensive copies versus copy-on-write.

We’ve learned how to maintain immutability in our own code using copy-on-write. But we often have to interact with code that doesn’t use the copy-on-write discipline. There are libraries and existing code that we know treat data as mutable. How can you pass your immutable data to it? In this chapter, we learn a practice for maintaining immutability when interacting with code that might change your data.

Immutability with legacy code

It’s time again for MegaMart’s monthly Black Friday sale (yes, they do one every month). The marketing department wants to promote old inventory to clear it out of the warehouse. The code they have to do that is old and has been added to over time. It works and is crucial for keeping the business profitable.

Image Vocab time

In this book, we’ll use the term legacy code to mean existing code (perhaps written with older practices) that we can’t replace at the moment. We have to work with it as is.

Image

Our copy-on-write code has to interact with untrusted code

Defensive copying defends the immutable original

Implementing defensive copies

The rules of defensive copying

Wrapping untrusted code

Defensive copying you may be familiar with

Copy-on-write and defensive copying compared

Deep copies are more expensive than shallow copies

Implementing deep copy in JavaScript is difficult

A dialogue between copy-on-write and defensive copying

Conclusion

Summary

Up next…

sitemap