Passive View and Cyclomatic Complexity
We have previously talked about cyclomatic complexity and set forth the goal of keeping the complexity for our methods down below 10. We have also talked about the goal of systematically refactoring any methods that we find to lower complexities whenever we make code changes. These are good and admirable goals for business logic.
But what about Passive View? Passive View is a slight variation on the Model View Presenter pattern designed to drive home the fact that the view should do very little processing. The view should be passive. Quiet literally the only code found in the view should be the implementation of the properties and the event handlers for the UI components. The properties should do the absolute minimal to interact with the user, and the event handlers should simply forward calls on to the presenter.
I cannot stress this enough, there should be no actual logic in the view.
The driving force behind the Passive View pattern is to simplify testing. Since it is harder to test the UI and the UI does not lend itself to automated testing, we want to move as much logic as possible to locations that are easier to test, class libraries. Testing aside, logic housed in class libraries is more reusable and can be shared across multiple UIs. In fact, the automated tests simply become a new UI.
All that being said, any method in the UI should have a cyclomatic complexity of 1!
Yep! You heard me correctly. One! If you find yourself writing a method, event handler or property in the UI with a complexity greater than one, stop and ask yourself why whatever logic you are implemented is in the UI. Chances are you will find that there is functionality that should be moved to the Presenter or a shared UI component.
I challenge everyone to identify UI code with a complexity greater than 1 that cannot be moved out of the View. Note that I said out of the View and not out of the UI layer. There are times when true UI processing may require some logical processing, but these are not so specialized that they cannot be removed from the View.