7 Staying immutable with untrusted code

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.
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.
