Skip to content

Composition

Devrath edited this page Feb 25, 2024 · 10 revisions

Composition (1)

Definition

When an object contains references to another object, It is called a composition

Example

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
  }

}

Why we use composition in object-oriented programming

Problem

  • Consider the FileCompressor class below, Observe that clearly it is violating the Single 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 thus single responsibility is preserved.
  • FilesHelper class encloses composition and the FileCompressorV3 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
    }
}

Goal of composition

  • 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.

Composition Benifits

  • Code reuse
  • Path to single responsibility
  • Better readability