1 min read

Guide to Single Responsibility Principle in Swift

Guide to Single Responsibility Principle in Swift
Photo by bady abbas / Unsplash

Single Responsibility Principle (SRP) is one of the five SOLID principles of object-oriented programming. It states that a class or module should have only one reason to change. In other words, a class should have only one responsibility or job.

SRP helps to keep the codebase maintainable, extensible, and testable. When a class has multiple responsibilities, changes to one responsibility can affect the other responsibilities, leading to unexpected bugs and difficulties in testing.

Here are some tips for applying Single Responsibility Principle in your Swift code:

  1. Identify the responsibilities of the class or module.
  2. Refactor the class to have only one responsibility by moving the code related to the other responsibilities to separate classes or modules.
  3. Ensure that the class or module is cohesive, i.e., all the code within the class or module relates to the same responsibility.
  4. Use descriptive and meaningful names for classes and methods to make it clear what their responsibilities are.

Let's see an example of applying Single Responsibility Principle in Swift:

class WeatherFetcher {
    func fetchCurrentWeather(forCity city: String) -> Weather {
        // Code to fetch current weather for a city
    }
    
    func fetchForecast(forCity city: String) -> [Weather] {
        // Code to fetch forecast for a city
    }
}

In the above example, the WeatherFetcher class has two responsibilities: fetching the current weather and fetching the forecast for a city. We can refactor this class to have only one responsibility:

class CurrentWeatherFetcher {
    func fetch(forCity city: String) -> Weather {
        // Code to fetch current weather for a city
    }
}

class WeatherForecastFetcher {
    func fetch(forCity city: String) -> [Weather] {
        // Code to fetch forecast for a city
    }
}

Now we have two separate classes, each responsible for fetching either the current weather or the forecast. This makes the code more maintainable and testable.

By following the Single Responsibility Principle, we can create cleaner, more modular code that is easier to maintain and extend over time.

Happy coding ✌✌🏻✌