15 April 2016

Views are Controls

by Amber Star

Why does the web seems to have such an elegant architecture? One reason is that the view layer is decoupled from everything else. The way the web works inherently enforces a clean separation of the presentation layer from the rest of the architecture. A web browser makes a request to the server, the server accesses the database and returns a result rendered in the browser. It turns out this is precisely the right way to think about any application architecture. If we can get the view layer decoupled from the application logic and data layers, we are on the path to a clean architecture. We have all heard about or experienced the “Massive View Controller” problem in iOS. The problems stem from putting application logic in view controllers. View controllers become filled with this logic, making it hard to test the logic, and also makes it hard to pull that logic out later when we want to refactor the application. What is the clearest way to separate the view layer from the logic and data layers? It is a problem that has received much attention. There are many patterns and names related to this problem. However, the reality is a simple principle.

Views are controls

Treat everything visual in the application as a control. Think of the entire screen as a control. Just like any other control in Cocoa. What is unique about controls? They have properties that change their visual presentation, and they have actions. In other words, they have inputs and outputs, but other than that, they are encapsulated. That is all a view is. A thin layer that presents information in some visual way where users can invoke actions. Perhaps Cocoa should allow the definition of components like controls easier. If components, and events were first-class citizens in Cocoa, we could define a new component, give it properties and events, and wire them up to IBActions just like we can with Cocoa controls allowing re-use of distinct UI.