Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Simplification

Part of the power of encapsulation (if you'll forgive such a dramatic turn of phrase) is that it offers a perfect opportunity for simplifying the processes of communication between objects, program layers, and everything in between.

The interface of any encapsulated entity should be as small and as simple as possible, rigidly applying a need-to-know approach. If your View Controller needs data from the Web, it shouldn't be creating HTTP requests, and it shouldn't even be telling the HTTP layer to make a request. It should probably not even be talking directly to any web-service layer at all. It should ask for information only, and leave all aspects of where that information comes from, and how it is obtained, to other layers of the program.

So, when you're stubbing data because the server-side software is still being written, or when you change which web service is being used, or when Google's API is changed to French, the View Controller should remain blissfully unaware that anything is different.

Similarly, the web-service layer should be completely user-agnostic, not knowing or needing to know where the HTTP responses are going. It should simply put the response into the closure it has been passed along with the request (a very simple mechanism in Swift, by the way) and call it.

While on the subject of the web-service layer, we should mention the facade pattern. The web service layer will probably contain a mish-mash of request types, HTTP methods, requests with headers and requests without, and all sorts of other stuff that can be hidden behind the facade. This facade offers a simple, limited channel through which other layers interact with the complex machinery behind it; a large and complicated set of structures is replaced, to all intents and purposes, by a single, smaller, and much simpler interface.

Here again, we can retain the specifications of the interface even when the whole thing behind it is tweaked, overhauled, or even swapped for something else.