Interface Segregation — SOLID Principles part 4

Bob Godwin
3 min readApr 27, 2018

--

Senja Norway

The Interface Segregation Principle deals separation of concerns. It states that a client should not be forced to implement or depend upon methods that it does not use. It is better to have many specific interfaces than to have a monolithic general purpose interface. The entire purpose of Interface Segregation is to reduce interface bloat or what is known as interface pollution and to favour code readability.

To better understand this principle let’s assume we have a requirement to “find the country, continent, percentage of each ethnic groups, population, economic community & languages of a nation”. While this might look simple at a first glance, it is not a trivial requirement when we apply the Interface Segregation Principle to this requirement.

We could start by modelling our continent, economic union, enthnicity and languages using the following example.

States could be structured using an “enum” as follows:

This is where Interface Segregation now comes into play. we could have an abstraction of the country, economic community, language and it’s ethnic groups into separate “protocols”.

One of the greatest advantages of Interface Segregation is composition. Your code base can be highly composable if you apply rigorously this principle.

The example below shows how “State” is receiving two properties from “Lingua” Interface through composition.

Using the same composition technics we can also extend the “Country” Interface, making it receive the “Ethnicity” Interface properties for free. Without creating any “Concrete Type”. This term is known as modular programming because any “Concrete Type” that conforms to “Country” doesn’t have to worry about it’s “Ethnicity” Interface implementations.

Before creating our “Concrete Type” that is going to represent the required specs we can take it further with the help of Interface Segregation by locking down the “init” method. This adds a little bit of constraints to the “Concrete Type” as shown in the “SovereignType” protocol below:

All set for a refined Interface to meet our requirements. We can now create the “Concrete Type” which summarises into a “Nation

Our requirement is now completely implemented and we can see the results below.

Taking a careful look at the above example we can see that “State” conforms to “Lingua” but not to “Community” or “Ethnicity” and therefore not forced to implement them. On the other hand a “Nation” conforms to all other protocol via the “SovereignType” Interface.

This series is covering the SOLID principles using Swift Language for practical examples, the previous path was on Liskov Substitution Principle and the article covers the final which is Dependency Inversion Principle For the complete playground you can find it here on the github repository.

Please feel free to reach out. I am looking forward to know what you think.

--

--