-
Notifications
You must be signed in to change notification settings - Fork 0
Composition
Devrath edited this page Feb 25, 2024
·
10 revisions
-
CONTENTS
When an object contains references to another object, It is called a composition
In the code below, When we create an object of a student, this object contains references to other objects.
class Student {
private Places places;
private Address address;
Student(Places places, Address address){
this.places = places;
this.address = address;
}
public void performStudy(){
// Performing studies
}
}
Problem
- Consider the
FileCompressor
class below, Observe that clearly it is violating theSingle Responsibility Principle
. - Because apart from compressing the file, This class also involved reading the files and writing the files.
public class FileCompressor {
public void compressFile(String filePath, String compressedFilePath) {
File file = new File(filePath);
byte[] uncompressedBytes = readFile(file);
byte[] compressedBytes = compress(uncompressedBytes);
writeBytesToFile(compressedBytes, compressedFilePath);
}
private byte[] readFile(File file) {
// read the bytes from a file
}
private byte[] compress(byte[] uncompressedBytes) {
// compress the bytes
}
private void writeBytesToFile(byte[] bytes, String filePath) {
// write bytes to the given file path
}
}
Solution
- We can delegate parts of the code to separate helper classes and modify the above code below.
- Basically for all the responsibilities that do not belong to this class, We have moved the responsibilities to the helper class.
- The solution of using the helper class helps in delegating the
secondary responsibility
to the helper class thussingle responsibility
is preserved. -
FilesHelper
class encloses composition and theFileCompressorV3
class is a composite class.
public class FileCompressorV3 {
private FilesHelper filesHelper;
public void compressFile(String filePath, String compressedFilePath) {
byte[] uncompressedBytes = filesHelper.readFile(filePath);
byte[] compressedBytes = compress(uncompressedBytes);
filesHelper.writeToFile(compressedFilePath,compressedBytes);
}
private byte[] compress(byte[] uncompressedBytes) {
// compress the bytes
}
}
- Reuse the responsibility of existing classes
- Basically if you have a collection of third-party classes, You can make a composite object of those classes and use them in your class.
- Delegating the secondary responsibility to other classes.
- Code reuse
- Path to single responsibility
- Better readability
.