Search code examples
ioscocoa-touchswiftcocoa-design-patterns

Class design dilemma - duplicated code for fairly close features


I'm building an app that displays objects of a certain type in different view controllers (three or four UITableViewController in this case). In one place they're going to be something like latest objects, in some other place search results and so on... So at the end of the day, the controllers are almost entirely similar. They only have a few variations. For example, the SearchTableViewController has a search bar and implements methods that are necessary for the feature. Other than that, classes "share" most of their code. What can I do to make this code truly shared and not just duplicated as it is at the moment?


Solution

  • If the UI is significantly different between the view controllers then you probably need to subclass. But if the differences are in the data model or the way the data is processed, then you can maybe use a generic view controller and design your data model to be more generic, so it can be viewed, sorted, or searched in unified manner.

    In my experience, however, there's a natural instinct in all developers to avoid duplication at any cost, and it often gets in the way of getting the job done. From a pragmatic point-of-view, I'd suggest implementing it in the most "obvious" way, and think about optimising it later. Only then will you know where there are duplications you can get rid of.