-4

There are two examples below that produce the same result. Trying to understand which one is better in which situations (Pros and Cons).

(1) Two classes with Dependency injection

class ServiceClass {

    init() {}

    func printHelloWorld() {
        print("Hello World")
    }
}

class ExampleClass {
    let service: ServiceClass

    init(service: ServiceClass) {
        self.service = service
    }

    func doSomething() {
        service.printHelloWorld()
    }
}

(2) Class conforming to protocol

protocol ServiceProtocol {
    func doSomething()
}

extension ServiceProtocol {
    func printHelloWorld() {
        print("hello world")
    }
}

class ExampleClass: ServiceProtocol {

    init() {}

    func doSomething() {
        printHelloWorld()
    }
}
Polisas
  • 491
  • 1
  • 9
  • 20

1 Answers1

1

As @Joakim has mentioned in the comments using the two approaches in combination could be the best implementation.

protocol ServiceProtocol {
    func doSomething()
}

extension ServiceProtocol {
    func printHelloWorld() {
        print("hello world")
    }
}

class ExampleClass {
    let service: ServiceProtocol

    init(service: ServiceProtocol) {
        self.service = service
    }

    func doSomething() {
        service.printHelloWorld()
    }
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47