Ch.3: Design Patterns: When to Use Adapter or Facade

Outline

Transcript

0:00 Adapter and Facade are design patterns for giving callers a useful interface: the operations they can ask an object to perform. We'll build both around a document publisher, then see what each one actually fixes. For example, the editor's save request fails when it asks the existing library to put a document at a file name. The library only offers send. Storage hasn't received the document. We asked it to save, and we haven't even reached storage. An adapter translates that request into the operation this library offers.

0:31 We'll follow the arguments into it and the result back out. Then publishing needs three steps: turn the document into bytes, save them, and record where they went. A facade gives that sequence a convenient entry point. We'll also check what remains if the last step fails. Before fixing that save, take a look at the caller's contract. Save from editor receives a storage object, a key and some data. Our key is the file name, roadmap.json. Its data is the document's bytes, ready to save. That put call takes the key first, then the data, and returns the result to the editor.

1:06 The three requirements beside it matter as much as that call shape. Store the supplied bytes, replace an existing value at the same key, and return the saved location as text. Memory Store already supports all three. Passing that object to the editor works. Old Vault can save our data too, but send takes the contents before the file name. It also returns a receipt containing several fields. Renaming the method alone would leave the arguments and result wrong. We need to preserve all three caller requirements.

1:36 How would you translate that exchange without changing this caller? That mismatch leads to Vault Adapter. It holds an Old Vault object in its vault field and passes the storage work to it while presenting put to the editor. According to Refactoring Guru, an adapter makes an existing interface fit its caller. Here, how does the file name avoid becoming the content? The bytes go first. The caller supplies key, then data, but the adapter passes data first and key second to Old Vault. That produces the receipt. The square brackets on the next line read its location field, and the adapter returns that text to the caller.

2:14 Now run the unchanged editor call with the adapter. The vault sends its record back. What reaches the editor? vault/roadmap.json. That's text from the receipt's location field; the record stays inside the adapter. And a second save with the same file name replaces the first bytes? Yes. This fictional Old Vault supports replacement, so the adapted object meets that requirement too. A different service may behave differently. Now imagine reviewing this adapter. If we own the editor, couldn't it call send directly and extract the location?

2:47 It could. The direct call on screen passes the bytes and extracts the location. If we then switch to Memory Store, which editor needs changing? The one calling send. We'd change that call to put and use its text result. For a single caller, I think I'd still choose that simpler code. I think the existing storage contract justifies ours. We can give the editor Memory Store or an adapted Old Vault while leaving its save operation unchanged. With direct integration, the editor knows the vault's inputs and receipt.

3:19 With our adapter, it only knows the put contract. Now take a publish request for the Roadmap document on screen: a title and a draft status. Here we're publishing its current contents, without changing that status field. First, the encoder turns those fields into bytes. Follow the two conversions below: structured text, then byte values. Once it's saved, what will the index let us look up? Storage returns a location. The index records it under our document key, so we can look up where the saved document lives.

3:51 Those results still need to reach the next operation. How does one publish call carry those results from step to step? With Publishing Facade, the encoder's bytes feed the storage call, then the returned location feeds indexing. Its caller asks for publish, a simpler entry point to that work. That lets the facade add an index entry linking the document key to its saved location. Only when indexing completes does the final line return a successful result. If another feature only needs storage, does it have to go through publish?

4:23 No. The underlying objects remain usable. A different feature can call the encoder or storage directly. Now expand that publishing call. The outer caller reaches the facade, which coordinates the encoder, storage and index. Follow the storage branch to see where our adapter fits. With Old Vault underneath, storage goes through Vault Adapter. The facade calls put, the adapter translates it to send, and Old Vault receives the inputs in its own order. On its return, the location leaves the adapter and reaches our publish operation.

4:56 The facade uses it to update the index and returns it when publication succeeds. So the facade didn't replace the adapter's job. It depends on the compatible storage interface the adapter provides at that inner boundary. Right. For example, supply Memory Store instead and our publish method uses put directly. We can remove the adapter because storage already has the required interface. I like that the publishing code stays put while storage changes. That store supplies a different location label.

5:25 If storage succeeds but the next call raises an error, does the saved file disappear? Let's say the index fails. The trace still starts with encoding, followed by a successful save in Old Vault. Then the attempted index update raises Index Unavailable. An exception is how this code reports that error to its caller. Execution leaves the publish operation at that point, so its last line doesn't return a success location. Hold on. While debugging that error, we could find a saved document with no index entry?

5:57 Exactly. The displayed storage still holds the content, but the lookup is empty. A facade can include recovery logic. This implementation doesn't undo the successful save. Our adapter translated the save successfully. Whether publishing should remove, retry or track a partly completed document is another requirement. Storage compatibility also covers the caller's replacement promise. Let's test that separately from indexing, using a service that allows each file name only once. Now try Write Once Vault. It accepts the same send inputs and returns the same receipt shape. The first save works.

6:32 What happens when the editor sends new bytes for roadmap.json? It rejects the second write instead of replacing the old content. The first saved value remains. We can put this object behind the same adapter, and the call still reaches send correctly. But our caller requires replacement, which this service cannot provide. Renaming an operation and extracting a receipt field can't create that missing behavior. We'd have to provide a real way to satisfy replacement, change the agreement, or reject this storage service.

7:03 That's a useful production integration check. Test the actual inputs, results and behavior the caller relies on, including repeated writes when replacement matters. The first vault could perform the needed storage behavior; its interface needed translation. That contrast gives us a way to decide when either pattern belongs in our code. With those checks in mind, use the four choices on screen. Preserve a caller's interface, simplify a feature's request, combine both needs, or keep direct code when it already fits.

7:33 Then test the promise behind that interface. In our example, the second save and the failed index update told us things the class names couldn't. The sources are linked in the description. Thanks for listening to Learning Podcasts.