Correct implementation of utility classes [Swift]

I am in the process of cleaning up my code as my class TableViewController

has gotten quite complete and long. To clean up the code, I would like to create a series of utility classes that provide methods for TableViewController

. These methods / functions in my current implementation can modify variables in the main one TableViewController

. Here's an example of my current setup:

class FooImplementation: NSObject {
    var viewController: Foo

    init(viewController: TableViewController) {
        self.viewController = viewController
    }
}

class FooUtility1: FooImplementation {
    // Methods
}

class FooUtility2: FooImplementation {
    // Methods
}

class Foo: TableViewController {
    var fooUtility1: FooUtility1
    var fooUtility2: FooUtility2

    override viewDidLoad() {
        fooUtlity1 = FooUtility1(self)
        fooUtlity2 = FooUtility2(self)
    }

    // Use of the methods...
}

      

Is there a better / versatile way to create and use these classes? And can these classes be combined into one class Utility

that has access to all methods FooUtility1

and FooUtility2

??

Thank!

+3


source to share


1 answer


I am not considering adding utility classes to a good design pattern, at least for the following reasons:

  • they can change the internal status of the view controller.
  • you need to "update" the element's properties to internal or public if they are private in nature.

Of course, I don't know what behaviors you want to move from view controllers to utility classes. My advice is to use one or more of the following:

  • create extensions controller extensions
  • create your own set of base view controllers inherited from UIViewController

    that will be used as superclasses for your final view controllers.
  • move some logic to external classes, but use the delegation pattern for interaction


The second case is the one I use a lot and the third is the one I applied to my last project, using better separation of concerns by implementing for each view displayed:

  • view controller, responsible for managing (but not displaying) the view and handling events received from its view (s)
  • the data source responsible for providing the data to be displayed in the view, as well as methods for adding / removing / updating as needed
  • a (hierarchy) implemented in a separate class in its own xib file.

This makes development a little more complex, but I end up with a light view controller and a view that is responsible for displaying data, handling events, and forwarding it to the view controller.

Please note that this is not a solution , just one possible solution . There are a couple of variables to consider, of course what you want to move from the view controller, and I think that's personal preference as well.

+6


source







All Articles