Spis Treści
Definition
The penultimate article on SOLID in object-oriented programming will be the principle of segregation of interfaces. This principle is simple to understand and simple to apply, so let's start:
Instead of using one large interface with many behaviors, use many smaller interfaces
I think we can intuitively understand why the above rule should be applied, but nevertheless let us verbalize our thoughts. The use of many small interfaces gives us great flexibility in building classes, while depriving us of the need to implement methods that we do not need.
Some example
Let's create classes that will handle files. Let's start by creating an interface that includes two methods for reading and writing a file and two classes that support different file types: read-only and writable.
public interface File {
void readFile();
void writeFile();
}
public class ReadWriteFile implements File {
@Override
public void readFile() {
//read file code here
}
@Override
public void writeFile() {
//write file code here
}
}
public class ReadOnlyFile implements File {
@Override
public void readFile() {
//read file code here
}
@Override
public void writeFile() {
//I don't need write file method here!!!
}
}
As you surely noticed, our interface as it is, is a poor fit for a read-only file. It would be better like this:
public interface ReadFile {
void readFile();
}
public interface WriteFile {
void writeFile();
}
public class ReadOnlyFile implements ReadFile {
@Override
public void readFile() {
//read file code here
}
}
public class ReadWriteFile implements
ReadFile, WriteFile {
@Override
public void readFile() {
//read file code here
}
@Override
public void writeFile() {
//write file code here
}
}
I think the above example is a sufficient idea of the essence of this principle and there is no need to dig deeper into it. However, if it is otherwise, I invite you to comment - I will be happy to answer.
Pingback: SOLID - podstawa programowania obiektowego – Wojciech Siwek
Comments are closed.