Where does regex go in an iOS app using the MVC design pattern?
I am writing an iOS app in swift and in like every app I need to request user input in several of my screens. I would like to follow good design patterns while designing my app and I am mainly focusing on the Model-View-Controller design pattern right now.
I will focus on the User Registration and Sign In screens to explain my scenario.
I have a User Registration Screen and a Sign In page which both share similar input fields such as: email and password
I have the following classes so far in order to follow MVC pattern:
The issue I am having now in terms of design is that in each view controller class I validating each input field mostly using regex. As you can probably guess this means that I have ended up with a lot of repeated code in both view controllers. For instance, I am validating the email and password exactly the same way in both view controllers.
Thus, how should I solve this and still follow MVC?
I am leaning towards having a Validator class with several validator functions that can be called and reused from each view controller and also perhaps a Regex class that will contain regex only? or should this be some type of Properties file?
Step back and think about this a little. What do your RegEx functions do? Validate and parse data. Is that a model (data storage) function? Not really. View? Not at all. Control? That seems like the best fit. A controller mediates between view objects and your data model, and also provides app control logic.
Now, as to the duplicate code problem. You have various options for dealing with this.
One is to create a common subclass for all your view controllers that provides your RegEx support.
Another approach is to create an extension for your view controller class and put the validation code there.
A third approach is to create your validator class, and to have your view controllers have a validator property (A "has a" relationship. Your view controller has a validator that manages validation for it.) You could even use a blend. Say you have a subclass of UIViewController that has the "plumbing" for a Validator class.
I lean towards the third approach. Keeping the validation functions out of the view controller itself makes it modular and more likely to be reusable. As you are designing your Validator class (assuming this is the approach you take) think about other use-cases where your Validator class might also be useful, and try to design to accommodate a wide range of use cases.
Asked in February 2016Viewed 3,601 timesVoted 6Answered 1 times