IV. Interface Segregation Principle in Swift
Continuing with the series of SOLID principles, we are going to talk about the Interface Segregation Principle.
In the previous post we talked about the Liskov Substitution Principle in which we created a common interface that was implemented by each class and in this way we could replace inherited objects of the same type. But what happens when we have a common interface with methods that will not be used by the other classes?
This is where the interface segregation principle comes in, which says that clients shouldn’t be forced to rely on interfaces with methods that they won’t implement. Therefore, it is preferable to separate the functionalities in different abstractions than to have a class that inherits an overloaded interface with methods that don’t use
Let’s see an example
Continuing with the previous example, we have the ‘LoginServiceProtocol’ protocol in which a method was defined for the sign in.
If we want to have more functionalities such as obtaining the data of a user, the posts, comments or the location of the user defined in the same protocol, we’ll have an interface overloaded with methods that won’t be used in each controller. Let us also remember the Open/Closed principle where each object must have a single responsibility.
Therefore we must identify and create different interfaces with the functionalities that are going to be implemented in each object or controller.
By this way we have in each object only the interface with the methods that we are going to use
To finish we have each controller with the type of service and its interface only with the necessary methods
In the next post we will finish the SOLID series where we will talk about the Dependency Inversion Principle.
See you soon! Happy coding👨💻