Extension vs. Class to use as a ViewModel

Viewed 303

What the advantages & disadvantages to each of these approaches pertaining to creating file that takes care of the view configuration to reduce a controllers file size.

Main Focuses Are:

  • Memory
  • Performance
  • Testing
  • Usability

This is the simplest, capable of working, example to demonstrate the question, but when many views are present using many methods do any of the above concerns alter when comparing the Extension & ViewModel Class?

Reminder: The ViewModel Class or Extension would be placed in a separate file.

ViewModel Approach

    class VC: UIViewController {
        lazy var viewModel: ViewModel {
            return (main: self)
        }()

        ovverride viewDidLoad() {
            super.viewDidLoad()

            initializeUI()
        }


        func initializeUI() {
            viewModel.configureView()
        }
    }



    class ViewModel {
        private let main: UIViewController

        init(main: UIViewController) {
            self.main = main
        }

        func configureView() {
            main.view.backgroundColor = UIColor.blue
        }
    }

Extension Approach

    class VC: UIViewController {
        lazy var viewModel: ViewModel(main: self)

        ovverride viewDidLoad() {
            super.viewDidLoad()

            initializeUI()
        }


        func initializeUI() {
            configureView()
        }
    }

    extension VC {
        func configureView() {
            main.view.backgroundColor = UIColor.blue
        }
    }
0 Answers
Related