Reputation: 8268
Let's say I am building a social network like Twitter and am trying to build a ProfileViewController
for display user info. First I would create a class named ProfileViewController
, and connect it to a UITableViewController
in Storyboard.
Now, I would like to customize the ProfileViewController
based on which user is viewing which profile. If I am looking at my own profile, I could have an "edit" button, whereas if someone else is looking at my profile, it would have a "follow" button. However the basic template is the same and it will still need to display common stuff like latest posts.
Some of the ways I could do this:
Use the same ProfileViewController
class. For example I could have multiple instances of ProfileViewControllers
on the Storyboard and use each of their restorationId
to distinguish between a ProfileViewController being called when a user taps "Profile" vs. a ProfileViewController
being called when a user visits someone else's profile.
Create different versions of ProfileViewController
for each purpose. I can create a class MyProfileViewController
exclusively for handling my own profile, and create a class UserProfileViewController
for handling other user's profile.
I am not sure what the best practice is. Can anyone help?
Upvotes: 2
Views: 1388
Reputation: 155
Although you are asking specifically about a Storyboard scene and a ViewController, the problem is more generically stated as:
'Should I have one class, which has logic to act in 2 different ways, given some state determining variable, or two different classes?'
The motivation for having one class, is because much of the logic is shared, and you don't want to duplicate code (and bugs). This is a good motivation.
The argument for having two classes is that you get rid of the if/else code, which can reduce bugs by reducing complexity and making the classes more well defined for their exact purpose. This is also a good motivation.
Fortunately you can have the best of both worlds. Have three classes.
The first class, A, will implement all of the logic common to both situations. In your case this will have all the logic except for the "Edit" Button for the "My Profile" view, and perhaps something like the "Add Friend" button for the "Other Profile" View.
The second class, B, and third class, C, will implement the logic for the "Edit button" and "Add friend button" respectively, AND also utilize the first class for common logic. You can have the relationship with the first class be either inheritance from class A, or delegation to an instance of class A. Using derivation is generally best in a case like this, where you can ensure all base class functionality is equally relevant to both subclasses, and you don't mind exposing the derivation in your public interface.
Upvotes: 2