Skip to content

Instantly share code, notes, and snippets.

@aliabbas90
Created January 31, 2023 21:28
Show Gist options
  • Save aliabbas90/c57ff4ca59a0ddaa343d12d009f2fa6c to your computer and use it in GitHub Desktop.
Save aliabbas90/c57ff4ca59a0ddaa343d12d009f2fa6c to your computer and use it in GitHub Desktop.

Protocol with Associated Types

Associated types are a powerful way of making protocols generic. Generic enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define.

S → Single-responsiblity principle O → Open-closed principle L → Liskov substitution principle I → Interface segregation principle D → Dependency Inversion Principle

  1. Single-responsiblity principle (SRP). A class should have only a single responsibility (i.e. changes to only one part of the software’s specification should be able to affect the specification of the class).

  2. The Open-Closed Principle (OCP) “Abstraction” Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

    • Open for extension: You should be able to extend or change the behaviours of a class without efforts.
    • Closed for modification: You must extend a class without changing the implementation.
  3. The Liskov Substitution Principle (LSP)“Decorator” objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

  4. Interface Segregation Principle (ISP) Clients should not be forced to depend upon interfaces that they don’t use.

//Wrong Way
//MARK:- Fat Protocol
//Describe the worker actions
protocol WorkerProtcol {
    func work() //work
    func eat() //eat
}

// Good way 
protocol WorkProtcol {
    func work() //work
}
protocol EatProtcol {
    func eat() //eat
}
  1. Dependency Inversion Principle (DIP)
    • High-level modules should not depend on low-level modules. Both should depend on abstractions.
    • Abstractions should not depend on details. Details should depend on abstractions.
//===========Abstraction================
protocol DataBaseProtocol
{
    func saveToDb(_ item : String)
}

//=============Details=================
//MARK:- Low Level
class CoreDataBase : DataBaseProtocol
{
    func saveToDb(_ item : String)
    {
        //implementation
    }
}

//MARK:- High Level
class DataStore 
{

//    A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
    
    let database : DataBaseProtocol // Abstraction
    init(_ database : DataBaseProtocol) {
        self.database = database
    }
    func saveToDb(_ item : String)
    {
        database.saveToDb(item)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment