开发者

Maintaining Single Responsibility Principle (SRP) with UIViewControllers

开发者 https://www.devze.com 2023-01-23 23:29 出处:网络
Sticking to Apple\'s guidelines, I create one subclass of UIViewController per screen of my iPhone applicatio开发者_如何转开发n.However I consistently find that these classes become very large, both i

Sticking to Apple's guidelines, I create one subclass of UIViewController per screen of my iPhone applicatio开发者_如何转开发n. However I consistently find that these classes become very large, both in terms of sheer lines of code and number of member variables.

By definition they end up being responsible for quite a number of different concerns (e.g. view life cycle, mediating between views and models, sometimes touch handling, control logic, managing alerts and other UI state).

Not only does this violate the Single Responsibility Principle but it also results in large swathes of code which are near impossible to unit test.

What responsibilities/concerns do you tend to divide off into new classes? What kinds of responsibilities do you think make good candidates for clean separation in the case of UIViewController subclasses?


This is an interesting question and I also struggle on how to properly separate responsibility. It all depends on the context but since testing subclasses of UIVieController can be a pain I try to move as much as I can into model classes. In the spirit of Skinny Controller, Fat Model.

When it comes to tables I have created a base model class for handling all the table view stuff, basically encapsulating what you get when you create a new Navigation Based Core Data project. The in the controller I just forwards the calls to my table model.

I'm trying to keep the methods of the controller as small as possible. Depending on the context I may have several model classes, each responsible for a specific part.

I have also looked into the possibility of using controller factories for getting detail controllers for certain data models.

UIViewController *detailController = [self.controllerFactory controllerForItem:item];
[self presentModalViewController:detailController animated:YES];

This way I can unit test that I get the proper controller for a specific data item without having to involve the parent controller.


With mine, I'm creating categories, abstract parents and using a variety of patterns I've learned in the Java world to reduce complexity and code duplication. But when it comes down to it, I still have one view controller per screen because every screen has at least one thing on it thats unique in some way. There just might not be much code left in the controllers thanks to the infrastructure I've placed around them.

0

精彩评论

暂无评论...
验证码 换一张
取 消